admin管理员组文章数量:1395016
is there a way to set the checkbox checked by default with the name attribute not class or id ?
<input type="checkbox" name="test">
i tried this but doesn't work:
document.getElementByName("test").checked = true;
Please provide a jsfiddle.
Thanks in advance!
is there a way to set the checkbox checked by default with the name attribute not class or id ?
<input type="checkbox" name="test">
i tried this but doesn't work:
document.getElementByName("test").checked = true;
Please provide a jsfiddle.
Thanks in advance!
Share Improve this question asked Feb 19, 2013 at 11:47 AbudeAbude 2,1628 gold badges36 silver badges60 bronze badges6 Answers
Reset to default 6Yes, it is possible. However, there is no getElementByName
method, there is only getElementsByName
. So if you have a single element with name "test"
, you can do:
document.getElementsByName("test")[0].checked = true;
Otherwise, you can set an ID to the element and use document.getElementById
.
DEMO: http://jsfiddle/GKFcR/
You can use document.querySelector
to select by attribute in any modern browser.
document.querySelector('[name=test]').checked = true;
http://jsfiddle/ExplosionPIlls/xpxHe/
You could do this with jQuery
$('input[name="test"]').attr('checked',true);
or Jquery 1.7+ use prop
method
$('input[name="test"]').prop('checked',true);
You can do it with jQuery or without:
$('input[name="test"]').prop('checked', true);
document.getElementsByName("test")[0].checked = true;
http://jsfiddle/UZB5Y/1/
Your example did not work as the method is getElementsByName
which returns an array of element.
Or if you control the HTML, you can just set them as checked on the server:
<input type="checkbox" name="test" checked="checked">
<input type="checkbox" name="test">
<input type="checkbox" name="test2">
<input type="checkbox" name="test2">
--------------------
// by jquery
$("input[name='test']").attr('checked','checked')
// by javascript
document.getElementsByName("test2")[0].checked = true;
here is example : http://jsfiddle/85x74/
Using jquery it is more simple :
<input type="checkbox" name="test">
In jquery:
$('input[name="test"]').attr('checked','checked');
In javascript:
document.getElementsByName("test")[0].checked = true;
本文标签: javascriptHow to set checkbox default by NameStack Overflow
版权声明:本文标题:javascript - How to set checkbox default by Name? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744110734a2591279.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论