一旦用户开始在文本字段中键入内容,如何选中复选框?如果javascript/html中的textfield为空,也可以取

How do you check a checkbox once user starts typing in a textfield? And also uncheck the checkbox if textfield is empty in javascript/html

本文关键字:javascript 如果 复选框 html 中的 也可以 为空 textfield 何选中 文本 字段      更新时间:2023-09-26

因此,我有一些代码可以在用户开始在文本字段中键入时选中复选框,但如果用户决定删除他或她开始键入的所有内容并将文本字段留空,我无法将其取消选中。有什么帮助吗?谢谢

<html>
<head> 
 <script type="text/javascript">
    function checkvalue(val)
    {
        if(val.value == '')
            document.getElementById('productCB').checked="false"
        else
            document.getElementById('productCB').checked="true"
    }
 </script>
</head>
<body>
  <g:checkBox id="productCB" value="searchProduct" /> Product:
  <g:textField id="productID" placeholder="Enter product here..." onkeypress="checkvalue(this)" />
</body>
</html>

falsetrue是布尔值,而不是字符串,因此,仅检查值长度与零的比较就会得到相同的结果,即布尔值。

您还应该使用onkeyup事件:

<html>
<head> 
 <script type="text/javascript">
    function checkvalue(val) {
        document.getElementById('productCB').checked = val.value.trim().length > 0;
    }
 </script>
</head>
<body>
  <input type="checkBox" id="productCB" value="searchProduct" /> Product:
  <input type="text" id="productID" placeholder="Enter product here..." onkeyup="checkvalue(this)" />
</body>
</html>

FIDDLE