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
checkbut then in yourifstatement looked forchecked. Secondarily, note that.checkedis a boolean value (trueorfalse) but you are comparing it to the string “1”. This happens to work, but is not recommended.Try:
Better than using
getElementByIdexplicitly in your handler, also, is to use the reference to the checkbox handling the event: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.