JQuery mobile radio changed event always fires even if already checked

I am using a radio button group containing two radio buttons to dynamically change the content of my page depending on which radio button is set. The content should be updated when the selected radio button is changed. So 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 fires only if I select an unchecked radio button. If I click on an already set radio button, nothing happens.

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

Now if I turn js

and css

jQuery mobile, change event always works, regardless of whether the switch has been tested: https://jsfiddle.net/6cnLgonk/19/ Note that the code is exactly the same as I connected only jQuery Mobile files to let radio buttons create styles automatically.

The desired behavior is only to only fire the change event if the radio button hasn't been checked yet. How can I do this with jQuery-enabled mobile buttons?

Is jQuery mobile js

overriding change event in some way? Do I need to manually set the switches manually? Thank you for your responses.

+3


source to share


1 answer


jQuery Mobile actually replaces radio inputs with dom shortcut elements, and it adds click handlers to those labels, which then fires a change event on the underlying radio buttons.

You can add a value attribute for 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

+3


source







All Articles