使用nextuntil禁用和启用select表单元素

时间:2013-07-11 22:02:41

标签: jquery forms

我正在尝试在选择单选按钮时激活一组选择下拉菜单,并在选择另一个单选按钮时停用。

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 个答案:

答案 0 :(得分: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/