2013-07-11 68 views
1

我试图激活一组选择下拉列表,当一个单选按钮被选中时,并且当另一个被选中时取消激活。使用nextuntil来禁用和启用选择表单元素

的jQuery:

$(':radio[name!="hours"]').change(function() { 
    if ($(this).filter(':checked').val() == "open") { 
    $(this).nextUntil("input","select").attr("disabled", false); 
    } else { 
    $(this).nextUntil("input","select").attr("disabled", true); 
    } 
}); 

HTML:

<form id="providerForm"> 
    <p><input type="radio" name="hours" value="no" checked="true"> There are no hours at this location</p> 
    <p><input type="radio" name="hours" value="yes"> Enter the hours below</p> 
    <span id="hoursList"> 
    <p><label for="monday">Monday: </label><span class="radios"><input type="radio" name="monday" value="closed"/> Closed</span> 
    <span class="radios"><input type="radio" name="monday" value="open"/> Open <select name="monStart" id="monStart" disabled></select> to <select name="monEnd" id="monEnd" disabled></select></span></p> 
    <p><label for="tuesday">Tuesday: </label><span class="radios"><input type="radio" name="tuesday" id="tueClosed" value="closed"/> Closed</span> 
    <span class="radios"><input type="radio" name="tuesday" value="open"/> Open <select name="tueStart" id="tueStart" disabled></select> to <select name="tueEnd" id="tueEnd" disabled></select></span></p> 
    </span> 
    <input type="submit" id="loginButton" name="submit" value="Add Hours" /> 
</form> 

小提琴是在这里:http://jsfiddle.net/BN6JD/

的选择框后点击 “打开” 启用 - 这是伟大的。但是,单击“关闭”后,它们不会再次禁用。我哪里错了?

回答

1

您正在过滤单个无线电输入(它是checked)而不是无线电组,并且nextUntill仅选择与当前标记无效的选定元素的下一个兄弟。还应该使用prop方法来代替attr。试试这个:

$('input[type=radio][name!="hours"]').change(function() { 
    $(this).closest('p') // select the closest parent `p` element 
      .find('select') // find `select` elements 
      .prop("disabled", this.value === 'closed'); // disable/enable the selects 
}); 

http://jsfiddle.net/6ELcA/

+0

真棒,谢谢!是否有理由将$(':radio [name!=“hours”]')更改为$('input [type = radio] [name!=“hours”]'),因为它们都做同样的事情? – CMH

+1

@CMH不客气,'input [type = radio]'比':radio'选择器快。我只是喜欢使用'tag [attribute]'选择器,没有具体的原因。 – undefined