【问题标题】:Checkbox with Confirmation and Stay with Original Checkbox Value if Cancel带有确认的复选框,如果取消,则保留原始复选框值
【发布时间】:2017-06-13 07:48:26
【问题描述】:

有一个复选框值。当更改我从用户那里询问的复选框值“你想在网站上显示这个项目吗?”或“你想在网站上隐藏这个项目吗?”

它工作正常。但问题是 cancel 选项。如果用户勾选复选框确认框将出现“你想在网站上显示这个项目吗?”。但即使用户选择取消它也会标记为选中。即使我使用document.getElementsByName("product").checked = false;再次取消勾选,它也不起作用。

JS 小提琴https://jsfiddle.net/9mvrfuyd/7/

注意:请不要使用 jQuery 解决方案。只有纯 JavaScript。

HTML

<input type="checkbox" name="product" onchange="change_property_status(this.checked);">Option 1

JavaScript

function change_property_status(status){
  if(status){
    status = 1;
    var con_message = confirm("Do you want to SHOW this item on website?");
    if(!con_message){
      document.getElementsByName("product").checked = false;
      return false;
    }
  } else {
    status = 0;
    var con_message = confirm("Do you want to HIDDEN this item on website?");
    if(!con_message){
      document.getElementsByName("product").checked = true;
      return false;
    }
  }

 }

更新:我没有为复选框使用 id 属性,但我使用了getElementsByName。所以这不是问题。

【问题讨论】:

    标签: javascript html checkbox


    【解决方案1】:

    只是在getElementsByName() 中缺少[0]

    document.getElementsByName("product")[0].checked = true;
    

    Updated jsFiddle

    getElementsByName() 方法返回所有元素的集合 具有指定名称的文档(名称的值 属性),作为 NodeList 对象。

    NodeList 对象表示节点的集合。节点可以是 通过索引号访问。索引从 0 开始。

    【讨论】:

      【解决方案2】:

      我认为getElementsByName 返回列表 a 的元素,因此您需要为其添加索引。 document.getElementsByName("product")[0].checked = false;

      【讨论】:

      • 现场演示仍然缺失[0]
      【解决方案3】:

      在输入标签内添加 id="product"。

      【讨论】:

      • 他使用 getElementsByName
      • 哦!刚刚注意到。我会再检查一遍。
      【解决方案4】:

      试试这个对你有帮助

      HTML

      <input type="checkbox" id="product" name="product" onchange="change_property_status(this.checked);">Option 1
      

      Javascript

      function change_property_status(status){
        if(status){
          status = 1;
          var con_message = confirm("Do you want to SHOW this item on website?");
      
          if(con_message == false){
              document.getElementById("product").checked = false;
            return false;
          }
        } else {
          status = 0;
          var con_message = confirm("Do you want to HIDDEN this item on website?");
          if(con_message == false){
            document.getElementById("product").checked = true;
            return false;
          }
        }
       }
      

      【讨论】:

      • 不工作......我认为使用getElementByName 代替getElementById 没有问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多