0

Hi there, quick question about onchange method usage. I have a couple of checkboxes and when I check/uncheck them I want a function to be called, therefore I have decided to use the onchange method. But I am not sure I get how this works. Take the following example:
HTML

<input type="checkbox" value="apple" name="fruit" checked="checked" id="apple" onchange="myFunction()"><label for="apple">Apple</label><br>

and here's the function:

function myFunction(){
    var update = false;
    console.log("update is " + update);

}

When the code runs, the message in the console is displayed even if I don't touch the checkbox...how's that possible? I would have thought that myFunction would run only if I had checked/unchecked the box
thanks

3
Contributors
8
Replies
10
Views
4 Years
Discussion Span
Last Post by Violet_82
0

AFAIK onChange isn't triggered properly because the checkbox does not have input focus. You may want to try onClick instead.

0

thanks pritaeas, but that means that I have to do all the checking in the function (ie if the checkbox is ticked or not). I thought if I use onChange, I don't need to check anything. I am not sure I understand this though, what do you exactly mean by input focus? Also, where is then onChange used?
thanks

0

Yes, you should check checked yourself. Input focus means that there is a cursor (for text based inputs). OnChange is used in text input, text area, file upload and select boxes. In jQuery this behaviour is extended to radio- and checkboxes. Perhaps that is causing the confusion.

Edited by pritaeas

0

ok thanks for clarifying the issue.
I have done what you said

<input type="checkbox" value="apple" name="fruit" checked="checked" id="apple" onClick="myFunction()"><label for="apple">Apple</label><br>

and here's the function:

function myFunction(){
    var update = false;
    console.log("update is " + update);
}

But get this: the console.log output is displayed in the console even if I don't touch the checkbox, so, same problem as before. I get the output when I click on it of course, but when the page load I get it too. What's going on!?

0

ehm...and so it is, sorry the script is about 700 lines and I didn't notice the call was also somewhere else, apologies. In that case I will try onchange again, just out of interest
thanks for your help

Edited by Violet_82

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.