Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get onchange callback on radio buttons, but only the one that was SET

I have a group of radio buttons with the same name, but different values. I'd like to do something like:

$("#langs").on("change", "[name=locale]", myfunction);

This works, but when I click on a new radio button myfunction gets called twice: once for the "old" radio button that is automatically getting unchecked, and once for the new one I'm clicking on.

changing onchange to onclick is not a solution, because I use it with jquery-mobile and it wraps the inputs with label, so the label is getting clicked, not the input.

like image 499
Gavriel Avatar asked Jun 08 '12 16:06

Gavriel


2 Answers

You can pass $(this) as an argument to myfunction and then inside myfunction check if the radio button is checked

$("#langs").on("change", "[name=locale]", function() { myfunction($(this)); } );

function myfunction(elem) {
    if(elem.is(':checked')) {
        // code here
    }
}
like image 147
Brian Glaz Avatar answered Sep 30 '22 18:09

Brian Glaz


Does this work for you? Following the jQM Docs

  • Example 1
  • Example 2 ( fun )

HTML:

<div data-role="page"> 
    <fieldset data-role="controlgroup">
        <legend>Choose a language:</legend>
        <input type="radio" name="langs" id="english-lang" value="en" />
        <label for="english-lang">English</label>
        <input type="radio" name="langs" id="korean-lang" value="ko" />
        <label for="korean-lang">Korean</label>
    </fieldset>
</div>​

JS:

$("input[name=langs]:radio").bind( "change", function(event, ui) {
    console.log('Lang: '+$(this).val());

    // Call function here
});
like image 43
Phill Pafford Avatar answered Sep 30 '22 17:09

Phill Pafford