I'm writing some code that highlights all <input type=radio />
within a "radio group" when any one of them is changed.
In the event handler for the radio "change" event, I use the following code to find all other similar radios:
radioHandler: function (event) {
var element = $(this);
var name = element.attr("name");
// Find all radios in the same group:
element.closest("form")
.find("input[type=radio][name='" + name + "']")
.each(function(){
... etc ...
});
},
This works perfectly if the radios are indeed contained within a form.
However, I also want it to work if there are radios outside the form too.
For example, assuming all radios use the same name
, the following represents 3 different radio groups (and all browsers behave this way):
o Radio A | o Radio B | o Radio C (Group - no form)
<form> o Radio D | o Radio E | o Radio F </form> (Group - form 1)
<form> o Radio G | o Radio H | o Radio I </form> (Group - form 2)
Also, for bonus points ... what if the element isn't part of the current document -- ie, it is contained within another "detached" context? The current solution works fine (because element.closest(...)
uses the element's context).
Instead of executing the .find on your form, execute it on your entire document:
$("input[type=radio][name='" + name + "']").each(function() {
... etc ...
});
Unless I'm not understanding the question here?
EDIT I didn't test the code below but it might give you the idea on how to do it.
radioHandler: function (event) {
var element = $(this);
var name = element.attr("name");
// Find all radios in the same group:
if (element.parents().find("form").length > 0) {
name.closest("form").find("input[type=radio][name='" + name + "']")
.each(function(){
... etc ...
});
} else {
$("input[type=radio][name='" + name + "']").each(function() {
if (!$(this).parents().find("form").length) {
... etc ...
}
}
}
}