复选框OnLoad的JavaScript条件

时间:2018-03-29 16:02:14

标签: javascript checkbox conditional-statements onload

我有一个复选框,用于确定是否隐藏或使元素可见。我的问题:是否还有一种方法可以包括如果复选框最初未在页面加载中取消选中以永久删除这些元素,以便无法调用它们,否则继续下面的内容?希望有道理。

function myEmail() {
    var emailBox = document.getElementById("checkemail");
    var emailradios = document.getElementById("emailradios");
    var emailOptOutSix = document.getElementById("emailOptOutSix");
    var emailOptOutForever = document.getElementById("emailOptOutForever");

    if (emailBox.checked == true){
        emailradios.style.visibility = "hidden";
        emailforever.style.visibility = "hidden";
        emailOptOutSix.checked = false;
        emailOptOutForever.checked = false;

    } else {
       emailradios.style.visibility = "visible";
       emailforever.style.visibility = "visible";
    }
}

1 个答案:

答案 0 :(得分:0)

有点不清楚你的要求。如果要在未选中复选框时删除项目(在页面加载时),则可以执行以下操作:

以下是工作版JSFiddle

应该注意的是,使用子字符串获取cookie并不是最佳做法。创建一个处理它的函数是明智的。这里可以找到一个例子。 Working with cookies

//gets the cookie for checked/not checked state
var checked = document.cookie;

//On window load
window.onload = function() {
  //Get the value of the cookie
  var emailBoxChecked = checked.substring(checked.indexOf("=") + 1);
  if (emailBoxChecked == "checked"){
      //set the state of the checkbox to true
      document.getElementById("emailbox").checked = true
      //If checked do something

  } else {
      //set the state of the checkbox to false
      document.getElementById("emailbox").checked = false
      //remove radio buttons that are contained within the emailRadios div
      var parent = document.getElementById("myForm")
      var child = document.getElementById("emailRadios")
      parent.removeChild(child)


  }
};


//Call this function when the checkbox is clicked
var emailChecked = function () { 
   var emailBoxChecked = document.getElementById("emailbox").checked
   if (emailBoxChecked){
      // store the state of the checkbox as checked in a cookie
      document.cookie = "email=checked";
   } else {
      // store the state of the checkbox as NOT checked in a cookie
      document.cookie = "email=unchecked";
   }
}