Reputation: 1129
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>
Upvotes: 0
Views: 104
Reputation: 303136
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.
Upvotes: 6