How can use AND statement in if with javascript?
Sebastian Wright
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=""></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></p> <div>
<select> <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></div> </div> </body> 3 Answers
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.
0You need to use &&
if ($(".select-box option[value='3']").attr('selected') && $(".select-box option[value='1986']").attr('selected'))
________________________________________________________^Logical operators:
&& = and
|| = or
! = notand you must change the select class from first select otherwise you will not get them both.
The second (outer) parentheses seem to be important too.