【问题标题】:Check and Uncheck Checkbox选中和取消选中复选框
【发布时间】:2015-11-24 22:55:01
【问题描述】:

为什么当我选中复选框时,当我取消选中它时它工作正常

<form method="get">
    <table id="row">
        <tr><th colspan="2" >Location</th></tr>
        <tr><td>Country:</td><td><select id="country" name ="country"  style="width:200px"></select></td></tr>
        <tr><td>City:</td><td><select name ="city" id ="state"></select></td></tr>
        <script language="javascript">
            populateCountries("country", "state");
        </script>
        <tr><td></td><td><input onclick="myFunction()" type="checkbox" name="manualentry" value="manualentry" >Manual Entry</td></tr>
        <script>
            var table = document.getElementById("row");
            function  myFunction() {
                if (document.getElementsByTagName('manualentry').checked = true) {
                    document.getElementById("row").deleteRow(2);
                    var row = table.insertRow(2);
                    var cell1 = row.insertCell(0);
                    var cell2 = row.insertCell(-1);
                    cell1.innerHTML = "City:";
                    cell2.innerHTML = '<input  type="text" >';
                } else {
                    document.getElementById("row").deleteRow(2);
                    var row = table.insertRow(2);
                    var cell1 = row.insertCell(0);
                    var cell2 = row.insertCell(1);
                    cell1.innerHTML = "City:";
                    cell2.innerHTML = '<select name ="city" id ="state"></select>';
                }
            }
        </script>
        <tr ><td  colspan="2" align="right" > <input type="submit" value="Submit"></td></tr>
    </table>
</form>

【问题讨论】:

    标签: javascript html checkbox


    【解决方案1】:

    几件事。 GetElementsByTagName 是错误的函数调用,该方法用于通过元素的实际 HTML 标签获取元素数组。请改用GetElementsByName。此外,此调用将返回一个数组,因此您需要指定它是哪个索引(它将是索引 0)。由于checked 已经是一个布尔值,所以不需要指定== true

    替换if (document.getElementsByTagName('manualentry').checked = true)

    if (document.getElementsByName('manualentry')[0].checked)

    【讨论】:

      【解决方案2】:

      您在 if 条件中忘记了 =

      if (document.getElementsByTagName('manualentry').checked = true) {
      

      试试

      if (document.getElementsByTagName('manualentry').checked == true) {
      

      【讨论】:

      • 与 == 什么都没有发生
      猜你喜欢
      • 2021-03-31
      • 2015-08-02
      • 2014-05-04
      • 2018-04-27
      • 2017-08-27
      • 2019-07-27
      • 2019-01-28
      相关资源
      最近更新 更多