Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a checkbox was actually clicked?

I've got a binding for multiple inputs.

$("#foo", "#bar", "#fooCheckbox", "#barCheckBox").bind("change", function() {
   // do something here
   // do something extra here if $(this) was actually clicked
});

Since there are other ways of initiating a change of an input, (jquery's .change() method for one), Is there a way to tell if a checkbox was actually clicked to cause the change event?

I tried focus however the focus event fires before a checkbox's change event so that doesn't work.

$("#foo", "#bar", "#fooCheckbox", "#barCheckBox").bind("change", function() {
   // do something here
   if($(this).is(":focus")) // do something extra here but focus doesn't happen here for checkboxes.
});

Edit #1

Sorry I don't really know how to clarify this further...I don't care if the checkbox is checked or not...I know what .is(":checked") is and how to use it. It doesn't help here. I only want to know if the checkbox was actually clicked in to trigger the change event.

Edit #2

I have a work around...I first bind clicks for inputs and selects and store the id of the element. Then in my change binding I check to see if the element that changed is the same element that was last clicked.

$("input, select").click(function() {
    var myId = $(this).attr("id");
    lastClickedStore.lastClicked = myId;
});

Then in the change binding I just check if the current ID equals the last clicked Id.

$("#foo", "#bar", "#fooCheckbox", "#barCheckBox").bind("change", function() {
   // do something
   if(lastClickedStore.lastClicked == $(this).attr("id")) // do something else.
}
like image 916
kasdega Avatar asked Nov 20 '11 05:11

kasdega


People also ask

How can I tell if a checkbox is clicked?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

How do you check if checkbox is checked or not in HTML?

getElementById('takenBefore'). addEventListener('click', event => { if(event. target. checked) { alert("Checkbox checked!"); } });

Does checkbox return true or false?

A checkbox field stores a string as its value, and a string as its text. Its value is either 'TRUE' or 'FALSE' , and its text is either 'true' or 'false' .


1 Answers

Bind to click instead of change. The click event will still be triggered when the check box's state is changed with the keyboard, but event.pageX and event.pageY will be 0 in that case, so you can write:

$("#foo, #bar, #fooCheckbox, #barCheckBox").click(function(event) {
    // Do something here...
    if (event.pageX > 0) {
        // Check box was clicked, do something extra here...
    }
});
like image 141
Frédéric Hamidi Avatar answered Sep 28 '22 14:09

Frédéric Hamidi