【问题标题】:how check box check and unchecked automatically复选框如何自动选中和取消选中
【发布时间】:2014-12-17 06:17:12
【问题描述】:

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

我们需要一个函数,在文本字段收到任何输入后立即检查复选框。如果文本字段中的所有输入都被清除(变为空),则该复选框应再次变为未选中状态。

有人能引导我走向正确的方向吗?

【问题讨论】:

  • 很简单,只需为文本字段 onchange 或 keyup 设置一个事件,检查文本字段中的值,如果它与选项标签中的值匹配,设置 attr('checked', true)

标签: javascript jquery cordova checkbox textfield


【解决方案1】:

尝试使用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>

【讨论】:

    【解决方案2】:

    您可以使用类似的更改事件处理程序

    //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>

    【讨论】:

      【解决方案3】:

      试试这个:-

      $('#textfield').on('change',function(){
        $("#checkbox").prop('checked',$(this).val().length);
      });
      

      或者您也可以使用keyup,而不是使用change 事件。

      Fiddle.

      【讨论】:

        猜你喜欢
        • 2015-08-02
        • 1970-01-01
        • 1970-01-01
        • 2019-05-25
        • 1970-01-01
        • 2018-04-20
        • 2013-01-19
        相关资源
        最近更新 更多