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

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

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

This works, but when I click on the new switch, myfunction is called twice: once for the "old" switch, which automatically turns off, and once for the new one that I click on.

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

+6
source share
4 answers

You can pass $(this) as an argument to myfunction , and then inside myfunction to check if the switch is on.

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

 function myfunction(elem) { if(elem.is(':checked')) { // code here } } 
+6
source

Does this work for you? Following jQM Docs

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 }); 
+6
source

As far as I know, you have no restrictions on using onclick evente with jquery in shortcut. If you have an identifier, you can use it. Say you have the following html:

 <label for="foo" id="whatever1">foo</label><input type="radio" name="radiogroup_0" value="foo" > <label for="bar" id="whatever2">bar</label><input type="radio" name="radiogroup_1" value="bar" > 

In your jquery you can add:

 $('#whatever1').click( function(){ //paste your code inside } ); 

The same for the other label of the radio book

 $('#whatever1').click( function(){ //paste your code inside } ); 

Hope this helps. Louis M.

0
source

How to try something like:

 <div data-role="fieldcontain"> <fieldset data-role="controlgroup" data-type="horizontal"> <input type="radio" name="langs" id="first" value="1" onchange="myfunction();"/> <label for="first">First</label> <input type="radio" name="langs" id="second" value="2" onchange="myfunction();"/> <label for="second">Second</label> </fieldset> </div> 

And then:

 function myfunction(){ if($("#langs option:selected")){ //do something, for example alert($("#langs option:selected").text()); } } 

This should only call the function once, because it contains inside the element that needs to be used.

0
source

Source: https://habr.com/ru/post/917647/


All Articles