使用JavaScript通过类型而不是名称来操作HTML输入(复选框)元素 [英] Using JavaScript to manipulate HTML input (checkbox) elements via type instead of name

查看:91
本文介绍了使用JavaScript通过类型而不是名称来操作HTML输入(复选框)元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个带有一些复选框输入元素的HTML表单,并且我想要一个Select All或DeSelect All按钮。但是,我不想依赖输入元素的名称(如这个例子),而是类型,因为我有多个不同名称的复选框组。有没有一种方法可以通过依赖类型而不是名称来检查和取消选中表单中的所有复选框输入元素?

编辑:我们依赖于YUI库,所以我有访问YUI如果提供了一个解决方案。

解决方案

这应该做到这一点:

 < script> 
函数checkUncheck(form,setTo){
var c = document.getElementById(form).getElementsByTagName('input');
for(var i = 0; i< c.length; i ++){
if(c [i] .type =='checkbox'){
c [i] .checked =设置;
}
}
}
< / script>

< form id ='myForm'>
< input type ='checkbox'name ='test'value ='1'>< br>
< input type ='checkbox'name ='test'value ='1'>< br>
< input type ='checkbox'name ='test'value ='1'>< br>
< input type ='checkbox'name ='test'value ='1'>< br>
< input type ='checkbox'name ='test'value ='1'>< br>
< input type ='button'onclick =checkUncheck('myForm',true);值=查询>
< input type ='button'onclick =checkUncheck('myForm',false);值=取消选中>
< / form>


I am implementing an HTML form with some checkbox input elements, and I want to have a Select All or DeSelect All button. However, I do not want to rely on the name of the input element (like this example) but rather the type because I have multiple checkbox groups with different names. Is there a way to check and uncheck all checkbox input elements within a form with JavaScript by relying on the type instead of the name?

Edit: We rely on YUI libraries, so I have access YUI if that provides a solution.

解决方案

This should do it:

<script>
function checkUncheck(form, setTo) {
    var c = document.getElementById(form).getElementsByTagName('input');
    for (var i = 0; i < c.length; i++) {
        if (c[i].type == 'checkbox') {
            c[i].checked = setTo;
        }
    }
}
</script>

<form id='myForm'>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='checkbox' name='test' value='1'><br>
<input type='button' onclick="checkUncheck('myForm', true);" value='Check'>
<input type='button' onclick="checkUncheck('myForm', false);" value='Uncheck'>
</form>

这篇关于使用JavaScript通过类型而不是名称来操作HTML输入(复选框)元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆