Alex Kibler
Alex Kibler

Reputation: 4954

jQuery .click function executes twice in a row

I'm working on my first program using jQuery, but I'm having an issue. I have a dialog pop up on pageLoad that asks the user to select a date and a turn. Right now, for debugging purposes, I have it alert every time .click() executes, and for some reason, it seems like it executes before the user clicks and immediately afterward.

There are three radio buttons, Turns 1, 2, and 3. When the user clicks Turn 1, the alert should say "1". When the user clicks Turn 2, the alert should say "2", etc. But for some reason, it alerts the previous value as well as the new one. I searched all of my code, and there is only one alert, so I can't figure out what is calling click() twice. I've tested it in IE and Chrome and it happened both times.

This is my .click() function:

$("#turn-radio")
    .click(function () {
    turnvalue = $("input[name='turn-radio']:checked").val();
    alert(turnvalue);
});

If you check this jsfiddle, you'll see the rest of my code, which will hopefully make it easier to figure out what my problem is.

Thanks!

Upvotes: 0

Views: 333

Answers (2)

Brett Weber
Brett Weber

Reputation: 1907

changing

$("#turn-radio") to $("#turn-radio label") 

causes only one popup displaying the previous value

But, personally i would

$("#turn-radio input").change( function() { /* do stuff */ } )

Upvotes: 1

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

You need to change selector: as your radio button IDs are different and you were giving name as a selector that's why you were facing that problem:

 $("input[name='turn-radio']")
        .click(function () {
        turnvalue = $("input[name='turn-radio']:checked").val();
        alert(turnvalue);
    });

Updated Fiddle

Upvotes: 2

Related Questions