开发者

Check all check boxes in MVC view [duplicate]

开发者 https://www.devze.com 2023-03-21 15:32 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Using JavaScript to manipulate HTML input (ch开发者_开发技巧eckbox) elements via type instead of name.
This question already has answers here: Closed 11 years ago.

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');
0

精彩评论

暂无评论...
验证码 换一张
取 消