如何复选框自动选中和取消选中
how check box check and unchecked automatically
我们有一个table
,其中有三个这样的td
:
.HTML:
<table style="width:100%">
<tr>
<td ><input type="checkbox" name="favcolor" id="checkbox" value="red"></td>
<td>Smith</td>
<td><input name="textfield" type="text" id="textfield" ></td>
</tr>
</table>
我们需要一个函数,在文本字段收到任何输入后立即选中复选框。如果清除了文本字段中的所有输入(变为空(,则该复选框应再次变为未选中状态。
有人能引导我走向正确的方向吗?
尝试使用input
事件
$(function() {
var chk = $('#checkbox');
$('#textfield').on('input', function() { //fire as user types/drag-drop/copy-paste
//replace all white-space and get the actual text length
//if lenght is greater than 0, mark it else un-mark
chk.prop('checked', this.value.replace(/'s/g, '').length);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
<tr>
<td>
<input type="checkbox" name="favcolor" id="checkbox" value="red">
</td>
<td>Smith</td>
<td>
<input name="textfield" type="text" id="textfield">
</td>
</tr>
</table>
您可以使用更改事件处理程序,例如
//dom ready handler
jQuery(function($) {
//a change event handler for the input field
$('#textfield').change(function() {
//based on whether the input has a value set the checked state
$('#checkbox').prop('checked', this.value.length > 0)
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="width:100%">
<tr>
<td>
<input type="checkbox" name="favcolor" id="checkbox" value="red" />
</td>
<td>Smith</td>
<td>
<input name="textfield" type="text" id="textfield" />
</td>
</tr>
</table>
试试这个:-
$('#textfield').on('change',function(){
$("#checkbox").prop('checked',$(this).val().length);
});
或者 除了使用change
事件,您还可以使用 keyup
.
小提琴。
相关文章:
- 如何在angularJS中编辑时,如果DB中的值为true,则设置复选框,如果值为false,则取消选中复选框
- 使用Jquery选择或取消选择ListView中的所有复选框
- 使用jquery选中/取消选中单个复选框
- 使用javascript在页面加载时取消选中所有复选框
- (取消)使用单独的复选框激活复选框列表
- jQuery-取消选中复选框
- 单击或取消选中复选框时,如何创建弹出的自定义窗口
- Javascript选中/取消选中所有复选框并将值写入文本区域
- dojo/cbtree取消选中所有复选框并选中选中复选框
- 通过选中和取消选中复选框来添加和删除数组中的值
- 当与之关联的 ng-model 为 false 时,Angularjs 复选框值不会取消选中
- 取消复选框未进行可视化更新
- 复选/取消复选框不能与prop功能一起工作
- 在剑道ui网格中上下滚动时取消复选框
- 检查条件后使用jQuery取消复选框
- 当另一个复选框被选中时,取消复选框,但如果被选中,也取消复选框
- JQuery .prop函数不工作,取消复选框
- 取消复选框绑定
- 如何在不取消复选框的情况下通过Ajax更新复选框列表
- 绑定点击事件后无法取消复选框