I would like to determine the most efficient way (using jquery, or dom) to get the value of a set of checkboxes if you have one of them.
This should be generic when the input checkbox is part of a form. However, is this x-browser safe, how to do this more efficiently, and what if the checkbox is not part of a form?
function (domCheckboxElm) {
var result = $.map($(domCheckboxElm.form.elements[domCheckboxElm.name]).filter(":checked"), function(e) {
return $(e).val();
});
return res开发者_Go百科ult;
}
Edit:
As a side note, performance is very important here. This algorithm is needed for forms with a few input elements and for forms with thousands. And many of my users have extremely old computers ('02, '04, '05).
First of all: Select values of checkbox group with jQuery
Performance really shouldn't be an issue, unless you've got thousands of checkboxes to go through in one pass. Your best bet would be to encapsulate the checkboxes within a div or other parent DOM object, which can then be used within jQuery to constrain its DOM search:
HTML
<div id="checkboxDiv">
<input type="checkbox" name="sample" value="isAPerson" />
<input type="checkbox" name="sample" value="isADog" />
<input type="checkbox" name="sample" value="isACat" />
</div>
jQuery
var checkBoxArray=[];
$("#checkboxDiv input:checkbox").each(function(){
checkBoxArray.push([$(this).attr("value"),$(this).attr("checked")]);
});
Here's the practical example (assuming you're already including jQuery):
<script type="text/javascript">
$("#checkboxDiv input:checkbox").click(function(){
var checkBoxArray=[];
$("#checkboxDiv input:checkbox").each(function(){
checkBoxArray.push([$(this).attr("value"),$(this).attr("checked")]);
});
$("#disp").empty().append(function(){
var outputStr="";
for (a in checkBoxArray){
outputStr+=checkBoxArray[a][0]+": "+checkBoxArray[a][1]+"<br/>";
}
return outputStr;
});
});
</script>
Then, in the body:
<div id="checkboxDiv">
<input type="checkbox" name="sample" value="isAPerson" />
<input type="checkbox" name="sample" value="isADog" />
<input type="checkbox" name="sample" value="isACat" />
</div>
<div id="disp"></div>
I think the solution I would have to go with is the one I proposed with a fallback on the generic "input:checkbox[name=" + elm.attr("name") + "]"
if the element is not part of a form.
精彩评论