Possible Duplicate:
Using JavaScript to manipulate HTML input (ch开发者_开发技巧eckbox) elements via type instead of name.
Why does this not work ? Please help. This is code to check all checkboxes on a MVC view.
<script type="text/javascript">
function SetAllCheckBoxes(doc) {
var c = new Array();
c = doc.getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox') {
c[i].checked = true;
}
}
}
</script>
<input type="checkbox" name="Test" onclick="SetAllCheckBoxes('PartialViewName')"/>
You're passing 'PartialViewName'
as a string when your function seems to use it as a document
object.
Try this js:
function SetAllCheckBoxes(obj) {
var c = new Array();
c = document.getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox') {
c[i].checked = obj.checked;
}
}
}
And wire up your toggler checkbox like this:
<input type="checkbox" name="Test" onclick="SetAllCheckBoxes(this)"/>
Working Example: http://jsfiddle.net/hunter/fA2w5/
With jQuery it is extremely simple:
<input type="checkbox" id="Test" name="Test" />
$("#Test").click(function(){
$("input:checkbox:not(#Test)").attr("checked", $(this).is(":checked"));
});
Working Example: http://jsfiddle.net/hunter/fA2w5/3/
Try to use jquery selector, if you can:
$("input:checkbox").attr("checked","checked");
Also, you should use the document
, not doc
in your code:
document.getElementsByTagName('input');
精彩评论