开发者

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

开发者 https://www.devze.com 2023-01-03 10:14 出处:网络
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 th

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开发者_如何学Python 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>


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

$('#theOptions1').trigger('change');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号