开发者

jquery reset conditional filter

I have 2 dropdown lists on my webform and using jquery trying to filter/reset filter 2nd dropdown elements based on 1st dropdown selection.

$(document).ready(function()
{
       $('#dropdown1').change(function(e)
       {
            switch ($(this).val())
            {
                 case "4":
                 //this removal works
                 开发者_如何学编程$('#dropdown2').filter(function()
                    {
                        return ($(this).val() == 16);

                    }).remove();
                    break;


                 .................    
                 default:
                 //how would I restore filter here? 

            }

       }

});

Removing part works, so it filters item with no problem, but I have difficulty restoring the filter on dropdown 2 if something else is chosen in dropdown 1. I was trying to use .hide() and .show() instead of .remove() but it doesn't seem to work on IE6 at least.


At the start of your document ready take a copy of the values in dropdown2 like this:

var drp2values = $('#dropdown2').html();

then whenever you want to reset the values in dropdown2 to its original state do this:

$('#dropdown2').html(drp2values);

The actual value in the var will be something like :

<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="16">16</option>

just tried it:

This code works:

$(document).ready(function()
{
var drp2values = $('#dropdown2').html();

       $('#dropdown1').change(function(e)
       {
            switch ($(this).val())
            {
                 case "4":
                 //this removal works...  now ;)
                 $('#dropdown2').find('option').filter(function()
                    {
                    alert('in4 filt' + drp2values + $(this).val());
                        return ($(this).val() == 16);

                    }).remove();
                    break;  
                 default:
                 //how would I restore filter here? 
                 $('#dropdown2').html(drp2values);
            }

       });

});

With this HTML

<BODY>
    <select id='dropdown1'>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>

    <select id='dropdown2'>
        <option value="11">11</option>
        <option value="12">12</option>
        <option value="13">13</option>
        <option value="16">16</option>
    </select>
</BODY>

The original code you posted where you said the remove worked, it didnt remove the individual option with value 16, it removed the entire dropdown as you were not geting the options before you filtered, you were removing the dropdown :)

Hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜