选中表单中的任何/没有复选框时,启用/禁用提交按钮 [英] Enable/disable submit button when any/no checkbox in form is checked
问题描述
我正在尝试使用jQuery动态地启用/禁用表单的提交按钮.
I am trying to use jQuery to dynamically enable/disable a submit button for a form.
HTML:
<form id="user-add-to-group">
<table class="group-list">
<tbody>
<tr>
<th>Voornaam</th>
<th>Achternaam</th>
<th>S/P-nummer</th>
<th>Email</th>
<th>Type</th>
</tr>
<tr>
<td>Name</td>
<td>Surname</td>
<td>No.</td>
<td>email@bs.com</td>
<td>student</td>
<td><input type="checkbox" name="user_add_to_group[]" value="75F0CE8F-4B6F-4E17-BC7B-0B06AAD84625"></td>
</tr>
</tbody>
</table>
<button disabled="disabled" type="button" id="participant_add_btn" name="participant_add_btn" class="btn btn-primary">Add</button>
</form>
还有jQuery:
$('table.group-list tr').on("click", function(){
$(this).find("input[type=checkbox]").trigger('click');
if($("#user-add-to-group input[type=checkbox]:checked").length>0){
$("#participant_add_btn").prop("disabled","false");
}
else {
$("#participant_add_btn").prop("disabled","disabled");
}
});
我想使整个表行都可单击,因此当单击tr时,jQuery会触发click事件.这行得通,但是我似乎无法弄清楚为什么以后无法启用我的按钮.我想在选中表单中的任何复选框时将其启用,而当所有复选框都没有时将其禁用.
I want to make the entire table row clickable, so the jQuery triggers a click event when the tr is clicked. This works, but I cannot seem to figure out why my button won't be enabled afterwards. I want to enable it when any checkbox within the form is checked, and disable it when none of them are.
如果需要更多信息,请告诉我.
If more info is needed, please let me know.
推荐答案
jQuery.prop
期望值是Boolean
,任何不为空的string
都应视为true
,因为它是真实值
jQuery.prop
expects value to beBoolean
, anystring
which is not empty is considred astrue
as it is truthy value
$('table.group-list tr').on("click", function() {
$(this).find("input[type=checkbox]").trigger('click');
$("#participant_add_btn").prop("disabled", !$("#user-add-to-group input[type=checkbox]:checked").length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="user-add-to-group">
<table class="group-list">
<tbody>
<tr>
<th>Voornaam</th>
<th>Achternaam</th>
<th>S/P-nummer</th>
<th>Email</th>
<th>Type</th>
</tr>
<tr>
<td>Name</td>
<td>Surname</td>
<td>No.</td>
<td>email@bs.com</td>
<td>student</td>
<td>
<input type="checkbox" name="user_add_to_group[]" value="75F0CE8F-4B6F-4E17-BC7B-0B06AAD84625">
</td>
</tr>
</tbody>
</table>
<button disabled="disabled" type="button" id="participant_add_btn" name="participant_add_btn" class="btn btn-primary">Add</button>
</form>
这篇关于选中表单中的任何/没有复选框时,启用/禁用提交按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!