开发者

Showing and hiding <option> with jquery

I have three selects (html drop down lists), all contain the exact same values (except the ids of selects are different).

Now I want to do this:

  • When a user selects some option in the first select the same option is hidden in the other two. This rule applies to other two selects as well.

  • If the option in the second select is changed again then the previously selected option must reappear in the other selects开发者_如何学JAVA.

I hope I was clear. I know this should probably be solved with javascript but I don't have enough knowledge of it to write an elegant solution (mine would probably be very long). Can you help me with the this?


$('#selectboxid').hide();

is the simplest way

http://api.jquery.com/hide/

try toggle it it matches your requirement

http://api.jquery.com/toggle/

you can call these onchange of the select box

if you want to hide individual options

use .addClass and add class to that option to hide it

http://api.jquery.com/addClass/


Little late the party, but here's a full working solution: HTML:

<select>
    <option value="Fred">Fred</option>
        <option value="Jim">Jim</option>
        <option value="Sally">Sally</option>
</select>
<select>
    <option value="Fred">Fred</option>
        <option value="Jim">Jim</option>
        <option value="Sally">Sally</option>
</select>
<select>
    <option value="Fred">Fred</option>
        <option value="Jim">Jim</option>
        <option value="Sally">Sally</option>
</select>

JavaScript:

$(document).ready(function() {
    $("select").change(function() {
       var $this = $(this);
       var selected = this.options[this.selectedIndex].value;
       var index = $this.index();
        $("select").each(function() {
             var $this2 = $(this);
            if($this2.index() != index) {
            $(this.options).show();
            var $op = $this2.children("option:[value='" + selected + "']");
            $op.hide();
            if($this2.val() == selected) {
                 if($op.index() + 1 == $ops.length) {
                    $this2.val($ops.eq(0).val());
                }
                else {
                    $this2.val($ops.eq($op.index() + 1).val());
                }
            }
        }
        });
   });
});

Also demonstrated here: http://jsfiddle.net/thomas4g/u2sbd/21/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜