简体   繁体   English

JavaScript onchange事件不起作用

[英]Javascript onchange event not working

I did this code up trying to hide a select input field until the check box is checked. 我做了这段代码,试图隐藏选择输入字段,直到选中复选框。 It works but when the page first loads these are all visible. 它可以工作,但是在页面首次加载时都可见。 I need them invisible until the check box is filled in. If I load the page then click the checkbox and then uncheck the check box the object disappears so I know it's working but why does it appear at the beginning and more importantly how do I stop it from doing that? 我需要它们在复选框被填充之前不可见。如果我加载页面,然后单击复选框,然后取消选中该复选框,则该对象消失了,所以我知道它正在工作,但是为什么它会出现在开头,更重要的是我如何停止是这样做的吗?

Code: 码:

 function doruc() { var elem = document.getElementById("secondhalf1"), checkBox = document.getElementById("pizza11"); elem.style.display = checkBox.checked ? 'block' : 'none'; }; 
 <input type="checkbox" id="pizza22" onclick="doruc()" name="halfHalf2" /> 

You need to call the doruc function in global scope after document ready state and then calling that function will set the style to none . 准备好文档状态后,需要在全局范围内调用doruc函数,然后调用该函数会将样式设置为none

<script>
    function doruc() {
        var elem = document.getElementById("secondhalf1"),
        checkBox = document.getElementById("pizza11");
        elem.style.display = checkBox.checked ? 'block' : 'none';
     };

   doruc();
</script>

I think it can solve your problem. 我认为它可以解决您的问题。

  if(pizza22) {
    secondhalf1.style.display="none";
  }
  pizza22.onchange = function() {
        if(secondhalf1.style.display==="none") {secondhalf1.style.display="";}
      else if(secondhalf1.style.display==="") {secondhalf1.style.display="none";secondhalf1};
  }

JsFiddle: https://jsfiddle.net/x22ugdmm/1/ JsFiddle: https ://jsfiddle.net/x22ugdmm/1/

Your name of ID in JavaScript is not matching to your element. 您在JavaScript中的ID名称与您的元素不匹配。 In JavaScript there is pizza11 and in input tag there is pizza22. 在JavaScript中有pizza11,在输入标签中有pizza22。 So look into that. 因此,调查一下。 2 nd reason is you didn't call your function, you just defined it. 第二个原因是您没有调用函数,而是定义了它。

 function doruc() { var elem = document.getElementById("secondhalf1"), checkBox = document.getElementById("pizza11"); elem.style.display = checkBox.checked ? 'block' : 'none'; }; doruc(); 
 <input type="checkbox" id="pizza11" onclick="doruc()" name="halfHalf2" /> 

Try this it will work. 试试这个,它将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM