javascript - onchange not working with radio button -
i have few radio buttons should call hider(something); when change, meaning when checked or unchecked. works, i.e. when checked call js function, however, if they're unchecked due selecting radio button group, not call js script again.
do need use else onchange?
this radio buttons @ moment:
<input name="ostype" type="radio" value="0" onchange="hider(solaris);">solaris <input name="ostype" type="radio" value="1" onchange="hider(linux);">linux
my hider function currently:
function hider(divid) { if ($(divid).is('.hidden')) { $(divid).removeclass('hidden'); } else { $(divid).addclass('hidden'); } }
since question still not answered correctly yet ranks quite high me in google "radio button onchange", here's proper solution still looking.
if you're using jquery, use jquery's attribute selector noted flavius stef.
op, it's not entirely clear code does. let's assume in code want add "hidden" class whatever radio button active.
$("your selector here").change(function() { $('input[name="' + this.name + '"]').removeclass("hidden"); $(this).addclass("hidden"); });
please note difference between $(this)
(the jquery object) , this
(the dom object). i'm removing "hidden" class every input goes same name, , add "hidden" class current input.
of course i'm assuming here you're not using duplicate names different inputs on page. note work radio buttons, radio button "change" event fires when activated, not when deactivated.
listening onchange on both checkboxes , radio buttons
in case, wanted add "checked" class active radio buttons , checkboxes. since checkbox fires "onchange" event both when checked , unchecked, needed bit of code.
$('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 set "checked" class if .is(":checked")
true
.
alternatively might want combine 2 functions like:
$('input[type="radio"], input[type="checkbox"]').change(function() { if(this.type == "radio") $('input[name="' + this.name + '"]').removeclass("checked"); $(this).toggleclass("checked", ($(this).is(":checked"))); });
either way, careful when listening onclick event not fire when input activated through keyboard navigation.
Comments
Post a Comment