如何复选框自动选中和取消选中

how check box check and unchecked automatically

本文关键字:取消 复选框      更新时间:2023-09-26

我们有一个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 .

小提琴。