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;