开发者

Do not allow duplicate dropdowns

I am guessing this is JS or jQuery but I'm not at all fluent with those (just starting to pick them up after many years of PHP).

I have 3 drop down boxes in a form that are all somewhat identical. All have a list of the same cites that are pulled from a MySQL database and populated via PHP. Let's say the cities are:

  • City 1
  • City 2
  • ...
  • City 8

The default values for the 3 drop downs will be:

  • Dropdown 1 is City 1
  • Dropdown 2 is N/A
  • Dropdown 3 is N/A

Basically I just need to make the drop downs work where a city selected in any of 3 automatically removes it from the other 2 drop downs. In the end 开发者_Go百科there can be no duplicate entries in the 3 pull down lists. Also I need it to happen dynamically (onChange event?) so that if they select City 4 in the first list it immediately is removed as an option from the other two drop down lists.

Hopefully this makes sense? Any help is appreciated!


Try this

   var selectedVal, $this, valuesToCheck;
$("select").change(function(){
   selectedVal = $(this).val();
   valuesToCheck = [selectedVal];
  $("select").each(function(){
     valuesToCheck.push($(this).val());
     $(this).find("option:disabled").removeAttr("disabled");
  }).each(function(){
        $this = $(this);
        $.each(valuesToCheck, function(){
            $this.find("option[value='"+this+"']").attr("disabled", "disabled"); 
        }); 
    }); 
});


$("#selectBox option[value='option']").remove(); --remove

$("#selectBox").append('<option value="option">option</option>'); --add

you can use the .change() to remove the option

$("select").change(function(){
  //remove option
})

what happens after a city is removed from select1 and select2 and the user changes the value of select3 to a different city, do you add the city back to the list?


And if he change back the value of dropdown 1 ? i guess you will have to put back the value removed? This would create a lot of ajax call to refresh the content of the other dropdown. I suggest you validate your condition on the onChange event and display a msg if you detect duplicates.

If you remove the entry like the other repsonse sugest.... if you select all the city 1 by 1 on the first dropdown, you will end up with no more entry in the 2 others ;-)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜