I have a strange problem which already made me bang my head against the wall for hours. I'm using jQuery to add an event listener to two radio buttons inside one control group. The changed event trigger an ajax request and the answer is used to exchange a part of the webpage below the radio buttons. The radio buttons themselves are not exchanged.
jQuery Code:
$(document).ready(function() {
$(":input[name= 'radio-choice-h-2']").on('change', function(){
$.post("process.php", {direction: $(this).attr("value"), lektion:$("#h1").text() + ".txt"})
.done(function(data) {
$(".question").html(data).trigger("create");
})
.fail(function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
});
});
html Code:
<fieldset data-role="controlgroup" data-type="horizontal" style="text-align: center" id="direction">
<input name="radio-choice-h-2" id="radio-choice-h-2a" value="atob" type="radio" >
<label for="radio-choice-h-2a">a → b</label>
<input name="radio-choice-h-2" id="radio-choice-h-2b" value="btoa" type="radio">
<label for="radio-choice-h-2b">b → a</label>
</fieldset>
The problem is, the change event always fires even if the radio button is already checked. I also checked, if the radio buttons are really checked by logging their checked status like this:
$(document).ready(function() {
$(":input[name= 'radio-choice-h-2']").on('change', function(){
console.log('#radio-choice-h-2a').is(':checked');
console.log('#radio-choice-h-2b').is(':checked');
});
The Output was always
true
false
for the first button and other way round for second button. I would have expected, that this only outputs, if the values change, but it always outputs no matter if the values changed. I used jQuery 2.1.3 and the problem exists in at least Firefox and Chrome. Haven't tested others.
UPDATE:
http://jsfiddle.net/6cnLgonk/15/
See this jsfiddle. I have included the external sources of jQuery mobile. If i do this, the desired behavior disappears and the .change() event is always fired even if the radio button is already checked....
What did i miss here? Thanks for your help !!
Okay after testing a bit, i found out, that the reason for this misbehavior was jQuery-mobile. Every time, i included the jQuery-mobile JS, the misbehavior showed. I had a look inside the source code and found that all input elements are replaced with styled labels by the jQuery-mobile JS hiding the original input field. The problem is, that radio-button and checkbox-buttons click events are handled together. Every time, a click event is triggered on a label, the changed event is fired on the hidden input, no matter if it is a radio-/checkbox button and no matter if it was checked before the click. I opened an issue for this bug. Answer was, the bug will not be fixed, because the next jQuery-mobile release will have different components for radio/checkbox buttons which do not suffer from this issue.