2015-05-20 49 views
0

我有一个按钮和选项列表。这个想法是,当用户点击按钮时,默认选项从禁用变为最大值。相反 - 如果输入未被检查,则默认再次被禁用。 但该值返回未定义。如果我将第一个和最后一个更改为数字值,则一切正常。怎么了?jQuery选择选项最后不起作用

<input class="input" type="checkbox" value="1" name="select-pot[]"> 
<select id="select" name="q-count[]"> 
<option disabled selected> -- choose -- </option> 
<option value="1">1</option> 
<option value="2">2</option> 
<option value="3">3</option> 
<option value="4">4</option> 
<option value="5">5</option> 
<option value="6">6</option> 
</select> 

jQuery(function(){ 

    jQuery(".input").click(function(){  

     var thefirst = jQuery(this).next('#select option:first').val(); 
     var thelast = jQuery(this).next('#select option:last').val(); 

     if(jQuery(this).is(':checked'))    
      jQuery(this).next('#select').val(thelast);  
     else   
      jQuery(this).next('#select').val(thefirst);  
    }); 
}); 

回答

1

.next()获取下一个兄弟姐妹,所以你需要获得选择和使用.find().children()算账:

var thefirst = jQuery(this).next('#select').find('option:first').val(); 
var thelast = jQuery(this).next('#select').find('option:last').val(); 
+0

完美。谢谢。 +1 – Tompo

1

由于ID必须是唯一的,有没有点在做这样的事情:

jQuery(this).next('#select option:first') 

jQuery('#select option:first') 

就足够了,再加上.next()会在这里失败,因为它会评估一个元素的同胞和过滤器对你传递的任何东西,但是你的过滤器会导致它不匹配任何东西。

相反,使用:

jQuery(".input").click(function() { 
    var thefirst = jQuery('#select option:first').val(); 
    var thelast = jQuery('#select option:last').val(); 
    if (jQuery(this).is(':checked')) jQuery('#select').val(thelast); 
    else jQuery('#select').val(thefirst); 
}); 

jsFiddle example

1

香草的JavaScript替代为未来的观众

(function() { 
 
    "use strict"; 
 
    var inputs = document.getElementsByClassName('input'), input; 
 
    for (var i = 0; input = inputs[i]; i++) { 
 
     input.addEventListener('click', function (e) { 
 
      e.target.nextElementSibling.lastElementChild.selected = e.target.checked; 
 
      e.target.nextElementSibling.firstElementChild.selected = !e.target.checked; 
 
     }, false); 
 
    } 
 
})();
<input class="input" type="checkbox" value="1" name="select-pot[]"> 
 
<select id="select" name="q-count[]"> 
 
    <option disabled selected>-- choose --</option> 
 
    <option value="1">1</option> 
 
    <option value="2">2</option> 
 
    <option value="3">3</option> 
 
    <option value="4">4</option> 
 
    <option value="5">5</option> 
 
    <option value="6">6</option> 
 
</select>