Even though this query about "radio button onchange" remains unanswered but is highly ranked on Google, here's a helpful solution for those still searching.
If you are utilizing jQuery, utilize jQuery's attribute selector as recommended by Flavius Stef.
If you want to signify an active radio button in your code by adding the "hidden" class, follow this example:
$("your selector here").change(function() {
$('input[name="' + this.name + '"]').removeClass("hidden");
$(this).addClass("hidden");
});
Remember the distinction between $(this)
(jQuery object) and this
(DOM object). The code removes the "hidden" class from all inputs with the same name and then adds it to the current input.
This method assumes unique names for different inputs on the page. Additionally, it only works for radio buttons since the "change" event triggers upon activation, not deactivation.
Responding to onchange events for checkboxes and radios
In my situation, I aimed to assign a "checked" class to active radio buttons and checkboxes. For checkboxes triggering the "onchange" event when checked or unchecked, extra code was necessary.
$('input[type="radio"]').change(function() {
$('input[name="' + this.name + '"]').removeClass("checked");
$(this).addClass("checked");
});
$('input[type="checkbox"]').change(function() {
$(this).toggleClass("checked", ($(this).is(":checked")));
});
The latter function uses toggleClass to apply the "checked" class based on .is(":checked")
being true
.
You may consider combining both functions like so:
$('input[type="radio"], input[type="checkbox"]').change(function() {
if(this.type == "radio")
$('input[name="' + this.name + '"]').removeClass("checked");
$(this).toggleClass("checked", ($(this).is(":checked")));
});
Always exercise caution when handling onclick events as they may not trigger during keyboard navigation.