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:
function toggleAction(){
var check = document.getElementById('checkb').checked;
if (checked == "1"){
alert("is checked");
}else{
alert("is not checked"); }
}
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
. Secondarily, note that .checked
is a boolean value ( true
or false
) but you are comparing it to the string "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:
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. This is considered a "best practice"; you should not be writing JavaScript directly in your HTML.
if(checked == "1")
应为if(check)
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.