Hello everyone I'm trying to run multiple javascripts and use AND statement. When user click an option which has value="1986" and click other option which has value="3", some text will appear. I have used AND statement in if statement but it doesn't work. Here is my code :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script></script>
<script type="text/javascript">
$(document).ready(function() {
$('#main').on('change', '.select-box', function() {
if ($(".select-box option[value='3']").attr('selected') & $(".select-box option[value='1986']").attr('selected')) {
$('#demo').html("Hello World");
}
});
});
</script>
<script type="text/javascript">
var x="",i;
for(i=1986;i<2013;i++)
{
x=x + "<option value='"+i+"'> " + i + "</option>";
}
$(document).ready(function() {
document.getElementById("demo2").innerHTML="<select class='select-box'>"+x+"</select>";
});
</script>
</head>
<body>
<p id="demo2"></p>
<div id="main">
<select class="select-box">
<option value="0">alert</option>
<option value="1">alert to</option>
<option value="2">no alert</option>
<option value="3">best alert</option>
</select>
<p><br/>
<div id="demo"></div>
</div>
</body>
AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False) OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False) NOT – =IF(NOT(Something is True), Value if True, Value if False)
You can use the logical AND (&&) and logical OR (||) operators to specify multiple conditions in an if statement. When using logical AND (&&), all conditions have to be met for the if block to run.
Using either “&&” or “||” i.e. logical AND or logical OR operator or combination of can achieve 3 conditions in if statement JavaScript.
You can use a Switch statement instead of if - else. also see AND OR and other logical operators. They are also also helpful in combining different if-else conditions into a single condition.
To use the AND statement, it should be &&
.
So for your if statement it should be
if ($(".select-box option[value='3']").attr('selected') && $(".select-box option[value='1986']").attr('selected')) {
$('#demo').html("Hello World");
}
Here is more information on boolean logic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With