简体   繁体   English

Javascript和复选框

[英]Javascript and Checkboxes

I'm trying to create a checkbox which will alter the form action on click. 我正在尝试创建一个复选框,该复选框将在单击时更改表单操作。 I'm starting out by setting it to alert a message depending on whether it is checked or not but nothing is happening. 首先,我将其设置为根据是否已检查但没有任何反应来提醒消息。 Please help me! 请帮我!

JavaScript: JavaScript:

function toggleAction(){
var check = document.getElementById('checkb').checked;
   if (checked == "1"){
    alert("is checked");
   }else{
    alert("is not checked"); }
}

HTML: HTML:

<INPUT TYPE="checkbox" id="checkb" onclick="toggleAction()">Add Another<br>

Your main problem is that you named your variable check but then in your if statement looked for checked . 您的主要问题是您将变量命名为check但随后在if语句中查找了checked Secondarily, note that .checked is a boolean value ( true or false ) but you are comparing it to the string "1". 其次,请注意, .checked是布尔值( truefalse ),但是您正在将其与字符串“ 1”进行比较。 This happens to work, but is not recommended. 碰巧可以正常工作,但是不建议这样做。

Try: 尝试:

if (check) alert("is checked");
else       alert("is not checked");

Better than using getElementById explicitly in your handler, also, is to use the reference to the checkbox handling the event: 比在处理程序中显式使用getElementById更好的方法是,使用对处理事件的复选框的引用:

document.getElementById('checkb').onclick = toggleAction;
function toggleAction(){
  if (this.checked) alert('yes');
  else              alert('no');
}

Note in the above how I also assigned the event handler programmatically using JavaScript instead of using the onclick="..." HTML attribute. 请注意上面的内容中,我还如何使用JavaScript以编程方式分配了事件处理程序,而不是使用onclick="..." HTML属性。 This is considered a "best practice"; 这被认为是“最佳实践”; you should not be writing JavaScript directly in your HTML. 您不应该直接在HTML中编写JavaScript。

if(checked == "1")应为if(check)

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

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