【问题标题】:Disable form controls based on previous selections根据之前的选择禁用表单控件
【发布时间】:2012-07-24 04:08:41
【问题描述】:

我有一个表,其中每一行中的一列都包含相同的 <select> 选项,如下所示:

<tr>
....
<td>..</td>
<td>
    <select id="gender">
        <option value="M">Male</option>
        <option value="F">Female</option>
    </select>
</td>
</tr>
<tr>
....
<td>..</td>
<td>
    <select id="gender">
        <option value="M">Male</option>
        <option value="F">Female</option>
    </select>
</td>
</tr>
<tr>
....
<td>..</td>
<td>
    <select id="gender">
        <option value="M">Male</option>
        <option value="F">Female</option>
    </select>
</td>
</tr>

假设我目前正在处理第二行,如何禁用第三行的选项?

【问题讨论】:

  • 请注意,您的 html 无效:id 应该是唯一的。

标签: jquery jquery-ui jquery-plugins jquery-selectors


【解决方案1】:
$(this).closest("tr").next().find("select").prop("disabled", true);

使用closest("selector")方法向上遍历到父元素(你也可以使用parents("selector")),使用next()跳转到下一个,向下遍历到find("selector")并使用prop()编辑表单元素.

当然,您可以将此行放入某种事件处理程序中,可能是由前一个 select 元素触发的 change 事件。但是,在你这样做之前,你需要确保你没有在 id 上加倍......否则 jQuery 将无法正常工作。

【讨论】:

  • 我已经在控制台中尝试过了,我收到警告 prop() 不是函数。但我得到了下一个 id
  • .prop() 是在 jQuery 1.6 中添加的 - 如果您使用的是早期版本,请改用 .attr()。 .attr("disabled", "disabled")
猜你喜欢
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-14
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
相关资源
最近更新 更多