jQuery mobile radio button changed event always fires even if already checked

1.1k views Asked by At

I'm using a radio button group containing two radio buttons to dynamically change the content of my page depending on which radio button is checked. The content should be updated, when the selected radio button changes. Therefor i added an event handler to the radio buttons.

html:

<fieldset data-role="controlgroup" data-type="horizontal" style="text-align: center" >
    <input name="radio" id="radio-a" type="radio" >
    <label for="radio-a">a → b</label>
    <input name="radio" id="radio-b" type="radio">
    <label for="radio-b">b → a</label>
</fieldset>

jQuery:

$(document).ready(function() {
    $(":input[name= 'radio']").on('change', function(){
        alert("DO SOMETHING");
    });
});

If i use some radio buttons without jQuery mobile everything works as expected. The change event is only fired if i select the unchecked radio button. If i click on an already checked radio button, nothing happens.

See this jsfiddle for demonstration: https://jsfiddle.net/6cnLgonk/21/

If i now include the js and css of jQuery mobile, the change event always fires, no matter if the radio button is already checked: https://jsfiddle.net/6cnLgonk/19/ Note that the code is exactly the same, i only linked the jQuery mobile files to let the radio buttons get styles automatically.

The desired behavior is to only fire the change event if the radio button is not already checked. How do i accomplish this using jQuery mobile styled radio buttons?

Is the jQuery mobile js somehow overriding the change event? Do i have to set the radio buttons checked somehow manually? Thanks for your answers.

1

There are 1 answers

3
ezanker On BEST ANSWER

jQuery Mobile actually replaces the radio inputs with label dom elements, and it adds click handlers to these labels that then trigger the change event on the underlying radio buttons.

You can add a value attribute to each radio button:

<fieldset data-role="controlgroup" data-type="horizontal" style="text-align: center" >
    <input name="radio" id="radio-a" type="radio" value="a" />
    <label for="radio-a">a → b</label>
        <input name="radio" id="radio-b" type="radio" value="b" />
    <label for="radio-b">b → a</label>
</fieldset>

Then you can save the current selection and then check it:

var CurrentSelection;
$(document).ready(function() {
    $(":input[name= 'radio']").on('change', function(){
        var clicked = $(this).val();
        if (clicked != CurrentSelection){
            CurrentSelection = clicked;
            alert("DO SOMETHING");
        }
    });
});

Updated FIDDLE