Teodoris
Teodoris

Reputation: 291

Get error using AND statement in javascript

you can understand what i mean here http://jsfiddle.net/ganymedes/eWghm/1/ Please select 1986 then select Hello finally select test2. I mean when you select test2 my script will display "0" text but it doesn't display.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script></script>
    <script type="text/javascript">
    var zero="0,00";
    var one="0,01";
    $(document).ready(function() {    
        $('#main').on('change', '.select-box', function() {    
            if ($(".select-box option[value='1']").prop('selected') && $(".select-box option[value='1986']").prop('selected')) {    
                $('#street').html("<option value='2'>test</option><option value='3'>test2</option>");    
            }
            if ($(".select-box option[value='1']").prop('selected') && $(".select-box option[value='1986']").prop('selected') && $(".select-box option[value='3']").prop('selected')) {
                 document.getElementById("demo3").innerHTML=""+zero;
            }    
        });    
      });
</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("forloop").innerHTML="<select class='select-box'><option>Empty</option>"+x+"</select>";
    });
</script>  
</head>
<body>  
    <p id="forloop"></p>
        <div id="main">
          <select class="select-box">
             <option>Empty</option>
             <option value="1">Hello</option>    
         </select> 
         <p></p>
         <select class="select-box" id="street">
            <option>Empty<option>
         </select>
      </div>    
    <p id="demo3">    
  </body>
</html>

Upvotes: 0

Views: 104

Answers (2)

Matt Whipple
Matt Whipple

Reputation: 7134

Every time you change any select this same handler is called. The first condition matches which resets the 2nd select's contents. All of this should be rewritten to be more targetted...but if you really want to go this route you should swap the order of if statements and make the second an elseif.

Upvotes: 2

dartaloufe
dartaloufe

Reputation: 46

Your three selectbox have the same class, so when the first one has the value 1, your second test is always true. Use id instead of classname to distinct your elements, it will be much more comprehensible (#year, #month, #day) and much more maintainable...

Upvotes: 1

Related Questions