Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery remove SELECT options based on another SELECT selected on change and on load

I'm using the following jQuery code to remove options from a select and it is working well. But instead of it only executing when the theOption2 select is changed I would also like it to work when the page is loaded depending on the selected item that is selected. I tried using the a copy of the script and changing the .change to .load and also tried using (window).load without the desired results. Essentially, I need the script to execute on change of the Options1 and on the loading of the page. Any help with this would be greatly appreciated.

<script type="text/javascript">
    $(document).ready(function() {
    //copy the second select, so we can easily reset it
    var selectClone = $('#theOptions2').clone();
    $('#theOptions1').change(function() {
        var val = parseInt($(this).val());
        //reset the second select on each change
        $('#theOptions2').html(selectClone.html())
        switch(val) {
            //if 2 is selected remove C
            case 2 : $('#theOptions2').find('option:contains(c)').remove();break;
            //if 3 is selected remove A
            case 3 : $('#theOptions2').find('option:contains(a)').remove();break;
        }
    });
});

</script>

<select id="theOptions1">
  <option value="1">1</option>
  <option value="2" selected="selected">2</option>
  <option value="3">3</option>
</select>
<br />
<select id="theOptions2">
  <option>a</option>
  <option>b</option>
  <option>c</option>
</select>
like image 564
John Sieber Avatar asked Dec 02 '25 09:12

John Sieber


1 Answers

Trigger the event at the end of $(document).ready(...:

$('#theOptions1').trigger('change');
like image 186
Gert Grenander Avatar answered Dec 05 '25 00:12

Gert Grenander