Peter Lur
Peter Lur

Reputation: 758

jQuery: Radio .change function, strange bug

I am trying to get the value of a selected radio after the .change event is triggered. I need to use an external function to do so but I cannot seem to get the correct value.

HTML:

<input type="radio" name="myradio" value="1.0"> 1.0
<input type="radio" name="myradio" value="2.0"> 2.0

jQuery:

$("input[type='radio'][name='myradio']").change(function() {

    //SHOWING GOOD VALUE
    radio_value = parseFloat($(this).val());
    alert(radio_value);

    TEST();

}

function TEST(){

    //SHOWING WRONG VALUE
    radio_value = parseFloat($("input[type='radio'][name='myradio']:checked").val());
    alert(radio_value); 

}

For example, if I click the radio 1.0 is checked and I click the radio 2.0, the above jquery code will output 2.0 for the first alert and 1.0 for the second. The TEST() function output the old value, it seems like if the radio event has not happened yet.

I need to find a way to get the good radio value in the TEST() function without transferring any parameter to it.

How can I do such thing?

Upvotes: 0

Views: 101

Answers (1)

Madbreaks
Madbreaks

Reputation: 19539

Try this in your TEST() function:

var radio_value = parseFloat($("input[type='radio'][name='myradio']").val());

Since they have the same name, you shouldn't need to worry about using :checked, and although I'm not sure why, it seems that may be the cause of what you're seeing.

ps: Do you really mean to be setting a global radio_value variable in these functions? I assumed "no" and prefixed the var declaration.

Upvotes: 1

Related Questions