Reputation: 15912
In some circumstances I have to detect radio-buttons changes. The problem is the app only have the ID of the button it is interested. For example, given that HTML piece:
<label class="required">Type</label><br/>
<span class="vertical">
<input checked="checked" id="diabetes_type-none" name="diabetes_type" type="radio" value="none" /><label for="diabetes_type-none">No diabetes</label><br />
<input id="diabetes_type-dm1" name="diabetes_type" type="radio" value="dm1" /><label for="diabetes_type-dm1">DM1</label><br />
<input id="diabetes_type-dm2" name="diabetes_type" type="radio" value="dm2" /><label for="diabetes_type-dm2">DM2</label><br />
<input id="diabetes_type-other" name="diabetes_type" type="radio" value="other" /><label for="diabetes_type-other">Other type</label>
<input class="small free" id="diabetes_type-other_more" name="diabetes_type-other_more" type="text" />
</span>
and given the ID "diabetes_type-other" the app must execute some code each time user checks or unchecks the "Other type" button. The code only must be executed when the user clicks on this radio button or when the user clicks on any other button unchecking a previous "Other type" checked button. If user clicks on DM1 and then clicks on DM2 the function shouldn't be executed. This is my approach:
$("#" + _var).change(function() {
alert('changed');
});
Problem here is the code is the function is triggered when user clicks on "Other type" but not when user unchecks this.
Other approach is to obtain radio name and then do something like this:
_radioName = "diabetes_type"; // Obtain programmatically
$("input[name=" + _radioName + "]").change(function() {
alert('changed');
});
Now the problem is this function is triggered always, on any button click and I need the function to be triggered only when user checks or unchecks the given radio button. You can play with this jsfiddle.
Upvotes: 2
Views: 1707
Reputation: 348972
Fiddle: http://jsfiddle.net/sn7eU/1/
Examine this code, it should meet your wishes:
var _radioName = "diabetes_type"; // Obtain programmatically
var _var = "diabetes_type-other";
#(document).ready(function(){
var lastChecked = false;
$("input[name=" + _radioName + "]").change(function() {
if(this.id == _var) lastChecked = true;
else if(lastChecked){
/*The radio input isn't "other". Check if the last checked element equals
"other" (lastChecked == true). If true, set lastChecked to false*/
lastChecked = false;
} else return; /*The input isn't "other", and the last checked element isn't
"other". Return now. */
alert('changed');
});
});
Upvotes: 4