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

Posted by John Sieber on Stack Overflow See other posts from Stack Overflow or by John Sieber
Published on 2010-06-09T23:38:40Z Indexed on 2010/06/09 23:42 UTC
Read the original article Hit count: 211

Filed under:
|

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>

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery