Teodoris
Teodoris

Reputation: 291

How can use AND statement in if with 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>

Upvotes: 16

Views: 93781

Answers (2)

aug
aug

Reputation: 11714

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.

Upvotes: 18

Mihai Iorga
Mihai Iorga

Reputation: 39704

You need to use &&

if ($(".select-box option[value='3']").attr('selected') && $(".select-box option[value='1986']").attr('selected'))
________________________________________________________^

Logical operators:

&& = and
|| = or
!  = not

and you must change the select class from first select otherwise you will not get them both.

Upvotes: 14

Related Questions