开发者

Showing an element based on a select choice - jQuery, HTML

I'm trying to show a second select element only if a certain option of a first one is selected.

Should be straight forward but it doesn't work.

So I have a few of select elements of class "one" each followed by a select o class "two". Within document ready function I first hide all of the selects of class "two": $('.two').hide(); works fine.

Then I have a function开发者_如何转开发 (also within document ready function) to show a next select of class "two" if a certain value is picked from the select of class "one".

$('.one').change(function() {  
    var two= $(this).next('.two');  
    if ($(this).val()==3){  
        if(two.is(':hidden')) {  
            two.fadeIn(50);  
        }else{  
            two.fadeOut(50);  
        }  
    }  
});

Can someone tell me what am I doing wrong?


Most likely you have other elements between the two selects, so you need to use the nextAll method like this

var two= $(this).nextAll('.two:first'); 

The next(selector) method will return the exactly next sibling if it matches the selector..

Additionally i believe that you have a wrong nesting of IFs.. Now you show/hide only if the value is 3 (both the hiding and showing happens if the value of the .one is 3)

Example : http://jsfiddle.net/UXS2X/

change

if ($(this).val()==3){  
        if(two.is(':hidden')) {  
            two.fadeIn(50);  
        }else{  
            two.fadeOut(50);  
        }  
    }  

to

if ($(this).val()==3){  
        if(two.is(':hidden')) {  
            two.fadeIn(50);  
        }  
    } 
 else{  
        two.fadeOut(50);  
     }


try this instead:

if ($('select.two option:selected').val()==3){
...
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜