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

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

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

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.

its better to use onclick bro...

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!?

Hmz... not being triggered elsewhere by accident?

does your checkbox already checked as default???

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.