Best Practice: Accessing radio button group
Looking for the best, standards compliant, cross browser compatible, forwards compatible way to access a group of radio buttons in the DOM (this is closely related to my other most recent post...), without the use of any external libraries.开发者_运维技巧
<input type="radio" value="1" name="myRadios" />One<br />
<input type="radio" value="2" name="myRadios" />Two<br />
I've read conflicting information on getElementsByName(), which seems like the proper way to do this, but I'm unclear if this is a standards compliant, forwards compatible solution. Perhaps there is a better way?
I'm not totally happy with this solution, but I did finally track this down in the Gecko DOM documentation.
name gets or sets the name attribute of an DOM object, it only applies to the following elements: anchor, applet, form, frame, iframe, image, input, map, meta, object, option, param, select and textarea.
HTMLElement.name = string;
var elName = HTMLElement.name;
var fControl = HTMLFormElement.elementName;
var controlCollection = HTMLFormElement.elements.elementName;
More here: https://developer.mozilla.org/en/DOM/element.name
So I suppose this is a standards compliant way of proceeding (though a best practice may not really exist...)
document.getElementById('myForm').elements.myRadios
I think the best thing going forwards is:
form.elements.myRadios
vs
form.myRadios
The reason being that according to the latest spec, elements.someName
will return an object of RadioNodeList
(if multiple elements have the same name) that contains a value
attribute indicating the checked item's value.
form.myradios
on the other hand will return an object of NodeList
which is just an ordered collection of items, and does not have any value
property.
Finding the checked items in radios and checkboxes has traditionally been a very painful exercise.
However, I am not sure how would we access all checked elements for checkboxes. Couldn't find that in the spec. Hope that is not missing.
精彩评论