Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can use AND statement in if with javascript?

Tags:

javascript

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>
like image 215
Teodoris Avatar asked Sep 11 '12 07:09

Teodoris


People also ask

How do you use an and operator in if?

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)

Can you put two conditions in an if statement JavaScript?

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.

Can IF statement have 3 conditions JavaScript?

Using either “&&” or “||” i.e. logical AND or logical OR operator or combination of can achieve 3 conditions in if statement JavaScript.

How do you write multiple if-else statements in 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.


1 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.

like image 62
aug Avatar answered Sep 21 '22 06:09

aug