Ivan Pandžić
Ivan Pandžić

Reputation: 373

Removing options from one select, based on the value in another select

My code reads 2 data from the database, and if those data are specific value, then it should remove values 2,3,4,5,6,7,8 from the select called smjer. Values from database are read in external .php script, and then sent back to web page using GET. My problem is next: In one specific case, when the second select in code is set to 3, then code should remove only 2nd and 3rd value from select smjer. I've done this with jQuery,and it works ,but my problem is that when i change value of other select, for example, from 2, I select value 3, nothing happens, so I have to refresh the page, so my changes would apply. Selects look like this:

<select name="smjer" class="smjer">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>

Second select:

<select name="godina" class="upis">
<option value="1" >1.</option>
<option value="2" >2.</option>
<option value="3">3.</option>
</select>

And the code for removal:

<?php }
if(($_GET['program1'])=='1'&&($_GET['stupanj_spreme1']=='2'))
{?>
<script>
$(document).ready(function(e) {
    var ary=[2,3,4,5,6,7,8];
var provjera=$('.upis').val();
if(provjera=='3')
{
    var ary=[2,3];
}
$('[name=smjer] option').filter(function(){
return ($.inArray(parseInt(this.value),ary) >-1);
}).remove();
});
</script>
<?php } ?>

I have been reading on net that something like this should be done with AJAX, but I don't know anything about AJAX, an I would like to avoid it. Tnx in advance.

Upvotes: 0

Views: 165

Answers (1)

thelr
thelr

Reputation: 1194

Instead of running your javascript once onready, bind it to the change event of the select in question:

$(document).ready(function(e) {
  // When the value of the select changes, run this:
  $('.upis').change(function(){
    var ary=[2,3,4,5,6,7,8];
    var provjera=$('.upis').val();
    if(provjera=='3')
    {
      var ary=[2,3];
    }
    $('[name=smjer] option').filter(function(){
      return ($.inArray(parseInt(this.value),ary) >-1);
    }).remove();
  });
});

Also, best practice: if you don't want "upis" to EVER apply to another element on this page, consider using id instead of class.

Upvotes: 2

Related Questions