Getting document.getElementByName with a substring
With the cons开发者_JS百科traint that you can't use jquery, what's the best way to get all element names that start with a specific string? (These are checkboxes, and I want to clear all the others when one is checked.
My solution works, but it seems less than optimal; is there a better approach?
What I'm doing is putting the checkboxes within a div and getting all the children of the div, and then comparing their name to what I'm looking for. Here's the javascript:
<script language="javascript" type="text/javascript">
function clearCheckboxes(name, id, divtag) {
if (document.getElementById(id).checked == false) {
return;
}
var listbox = document.getElementById(divtag);
var list = listbox.childNodes;
for(var i = 0; i < list.length; i++) {
if (list[i].type != "checkbox") continue;
if (list[i].id == id) continue;
if (list[i].name.substr(0, name.length) == name)
{
list[i].checked = false;
}
}
}
and then the html looks like this:
<div id="tag_div_2">
<input type="checkbox" name="tags_Type_4" id="4" onclick="clearCheckboxes('tags_Type_',4,'tag_div_2');" />3 Stone Ring
<input type="checkbox" name="tags_Type_3" id="3" onclick="clearCheckboxes('tags_Type_',3,'tag_div_2');" />Engagement Ring
<input type="checkbox" name="tags_Type_2" id="2" onclick="clearCheckboxes('tags_Type_',2,'tag_div_2');" />Solitaire
<input type="checkbox" name="tags_Type_5" id="5" onclick="clearCheckboxes('tags_Type_',5,'tag_div_2');" />Wedding Set
</div>
I think I'd just use "getElementsByTagName()".
var inputs = document.getElementById('tag_div_2').getElementsByTagName('input');
var checkboxes = [];
for (var i = 0; i < inputs.length; ++i)
if (inputs[i].type === "checkbox" && inputs[i].name.substr(0, name.length === name)) {
checkboxes.push(inputs[i]);
}
Of course you don't have to filter by type if you know that's not necessary due to your naming conventions.
These are checkboxes, and I want to clear all the others when one is checked.
Why not use a radio button instead?
精彩评论