Avatar of stargateatlantis
 asked on

toggle check box

In jQuery I am trying to figure out how to do a checkbox toggle.  There is so many different ways.  So basically if  you have a check box named myCheck.  When checked it will be checked and alert I am checked.  When its un-checked it will alert "I am un checked".  What to use or do use .on() because .live() is deprecated.

Avatar of undefined
Last Comment

8/22/2022 - Mon

what about :
$(":checkbox[name='myCheck']").click(function() {
//$("body").on("click", ":checkbox[name='myCheck']", function() {
    alert( $(this).is(":checked")?"I am checked":"I am un checked" );

Open in new window

test page : http://jsfiddle.net/Fw3ry/
Kiran Sonawane

Basically .on() is used when HTML is rendered dynamically ( e.g. you loading html using ajax call) otherwise you can go with .click () as example given by @leakim971

I use this code:

    $(":checkbox[name='myCheck']").change( function() {
        alert( $(this).is(":checked")?"I am checked":"I am un checked" );
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Jon Norman

The use of live() and delegate() have both been deprecated in favour of on(). Use change() if the element will be there when you inject the event to it.

If the element is going to be added later then you will need to delegate the click function to an element higher in the dom, for example you add the element to a div during a different function - e.g. an ajax function - load(). To do this you use the on() function. For example:
    $(document).on("change",":checkbox[name='myCheck']",function() {
        alert( $(this).is(":checked")?"I am checked":"I am un checked" );

Open in new window

In this case the click event is "attached" to the document object, but works on any checkbox with name myCheck, it is actually working on the checkbox so the this variable is the checkbox.

I noticed the examples that are simplified if else statements can you put the if else statements in long form

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question