开发者

jQuery indexOf select box manipulation

I'm trying to figure out how to remove options from a select box when that option has been selected in an adjacent select box. Basically the user has the option to add multiple records here via select boxes, but I want to remove the list of options available to them so that, for example, they can't enter the same value in two select boxes.

When an Add More button is clicked, I fade in the next select box container. A number of select boxes have been generated by PHP and I use JS to hide them. Each select box has a unique number appended to the ID, so i want to access those select boxes which contain the string "other_pet_types", then I want to iterate through the currently visible ones and build an array of the values which have been selected, which I will then remove from the list of options in the newly displayed select box.

This is what I have so far, but it's definitely not right - I can't get the initial test on the ID to work.

Any pointers greatly appreciated as i realise i'm pretty wide of the mark at the moment!

 var vals = new Array();
//build array with currently selected options
    $('p.mult_entries select').each(function(){
            vals += $(this).val();
    });
    $("p.mult_entries:hidden:first").fadeIn("slow", function() {
            $(this).find(('select').attr('id').indexOf('other_pet_types') > 0).each(function(){
            console.log($(this).val()); //as expected prints nothing - need to iterate through the options of the above select
                //once i extract the correct values, iterate through new select box and use inArray to remove options where that value already exists in one of previous select boxes
        });
    });开发者_Python百科


I made a quick jsFiddle based on your description that works. Instead of building a separate array, it just itterates through the select options. You will likely want to add logic for changing the selection and re-enabling your previous choice. You can use jQuery's .data() function to store the value so you can retrieve it after the change....or you can save it to a cookie. This should get you started, though.


The way you're building your array is wrong. You're building it like a string, not an array. This should work:

$('p.mult_entries select').each(function(){
  vals[vals.length] = $(this).val();
});

The way you're finding the appropriate select boxes can be turned into just a selector rather than a number of functions:

$(this).children("select[id^=other_pet_types]").each(function(){
  //do stuff here
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜