1

I have a page where a series of checkboxes are displayed next entries from a database, they each have an onClick event to do an Ajax write of their value to the database.

I want to have a button on the form that toggles all the checkboxes, so I used the following function/jQuery:

function toggle_chk_links(){
    $(".chk_user_link").click();
};  

It works fine visually, the only problem is that although it triggers the onClick event as required the checkbox is read with it's old value, so the database gets the opposite value to the one required! This is the line reading the checkbox in its' onClick event:

active=Number($("#chk_brandlink"+brand_ID).prop("checked"));

I need users to be able to manually click on each checkbox, as well as toggle them all, ideally using one onClick function call. Any suggestions?

2
  • is it happening only on IE or other browsers too Commented Feb 4, 2012 at 18:41
  • Firefox currently, not tried in others Commented Feb 4, 2012 at 18:57

1 Answer 1

4

The easiest solution is to handle the onchange event instead of the onclick event.

$(".chk_user_link").change(function() {
  // your change handler
});

Example: http://jsfiddle.net/7zHRm/1/

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks - the problem is, each checkbox has an onclick event passing two variables to an ajax write, which would be hard to replicate using a general jquery change handler
You could use a distinct (on)change handler for each checkbox instead of onclick handlers. So just turn "onclick" to "onchange" and it should work, or am I missing something?
Edit: Just used onChange rather than onClick on each checkbox and it worked a charm, thanks. Are you aware of any cross-browser issues, controls needing to lose focus etc?
At least in modern versions of IE, Firefox and Chrome this is not the case. I don't know about older browsers, though. Change even gets called before click, if you click on the checkbox.
This was bugging me for hours... x:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.