复选框切换时禁用输入字段(JQuery) [英] Disable input field when checkbox toggled (JQuery)
问题描述
我有一个复选框列表,每个复选框都有一个输入字段。如果选中该复选框,则必须禁用输入字段。
示例:
I have a list of checkboxes and with every checkbox, there is an input field. If I check the checkbox, the inputfield has to be disabled. Example:
Checkbox 1 - Input 1
Checkbox 2 - Input 2
Checkbox 3 - Input 3
真实代码:
<table id="food" width="580px">
<tr>
<th colspan="5">Eten</th>
<tr>
<td><input type="checkbox" name="checkbox_1_1" value="" /></td>
<input type="hidden" name="todo_1_1" value="7" />
<td>Braadworst</td>
<td>7</td>
<td><input type="text" name="item_1_1" size="4" value="" /></td>
<td></td>
</tr>
<tr>
<td><input type="checkbox" name="checkbox_1_2" value="" /></td>
<input type="hidden" name="todo_1_2" value="5" />
<td>Witte worst</td>
<td>5</td>
<td><input type="text" name="item_1_2" size="4" value="" /></td>
<td></td>
</tr>
</tr>
</table>
只有具有相同编号的输入字段可能被禁用...
Only the input field with the same number may be disabled ...
通过Google我发现: http://techchorus.net/disable-and-enable-input-elements-div-block-using-jquery
Through Google I found: http://techchorus.net/disable-and-enable-input-elements-div-block-using-jquery
该示例完美无缺,但有没有办法在不预先定义名称的情况下做到这一点?在我的情况下,不可能知道名称,所以他们必须在切换复选框时确定,不是吗?
The example works perfectly, but is there a way to do this without pre-defining the names? In my case, it is impossible to know the names, so they have to be determined when toggling the checkbox, no?
有什么建议吗?
推荐答案
首先对标记进行一些修正:隐藏的输入需要在< td>
并且标题行需要关闭< / tr>
,然后你可以这样做:
A few corrections to the markup first: that hidden input needs to be inside a <td>
and the header row needs a closing </tr>
, then you can do this:
$('#food').delegate(':checkbox', 'change', function() {
$(this).closest('tr').find('input:text').attr('disabled', !this.checked);
});
$(':checkbox').change(); //set state initially
你可以在这里看到一个演示,我们正在使用 .closest()
以获得< tr>
,然后查找<$ c的输入$ c> [type = text] 使用 .find( )
和 :text
。
You can see a demo here, we're using .closest()
to get up to the <tr>
, then finding inputs of [type=text]
using .find()
and :text
.
这篇关于复选框切换时禁用输入字段(JQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!