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=""></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>

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.

0

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.

1

The second (outer) parentheses seem to be important too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest