Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i make a checkbox fire a function?

I have a checkbox inside a <label> and i want that checkbox, when checked or unchecked, to trigger a function. I attached a onchange trigger to the checkbox but in IE6 the trigger only fires after the focus is turned away from the checkbox, while in FF3 and Chrome it fires right away. I removed the onchange trigger and attached a onclick trigger to the <label> but now the trigger fires twice when the label is clicked once (does enyone know why?)...

My question is: how can i make the checkbox fire a function when it is checked or unchecked by a click on it or on it's label.

Thanks.

like image 796
Angoras Rids Avatar asked Dec 28 '25 12:12

Angoras Rids


2 Answers

Assuming you don't want a fancy ASP / JQuery solution, just attaching the function to the onClick of the checkbox itself should work fine.

(Of course, you'll need to inspect the current state of the checkbox in the function if you want to have the function behave differently based on if the checkbox is checked or not.)

like image 184
Electrons_Ahoy Avatar answered Dec 31 '25 02:12

Electrons_Ahoy


As "Electrons_Ahoy" says, you should be able to simply attach an onclick handler to the checkbox element. This handler should also get called when the user clicks on the label instead of the checkbox.

HTML:

<label><input type="checkbox" id="myCheckbox" />My Checkbox</label>

JavaScript:

document.getElementById("myCheckbox").onclick = function() {
    if (this.checked) {
        alert("Checkbox was checked.");
    }
    else {
        alert("Checkbox wasn't checked.");
    }
};

The above code seems to work correctly in Safari 4 and Firefox 3 (I'm not sure how it would work in IE).

Steve

like image 21
Steve Harrison Avatar answered Dec 31 '25 02:12

Steve Harrison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!