Abude
Abude

Reputation: 2162

How to set checkbox default by Name?

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!

Upvotes: 2

Views: 594

Answers (6)

Tarun Kumar
Tarun Kumar

Reputation: 518

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;

Upvotes: 0

Sunil Dodiya
Sunil Dodiya

Reputation: 2615

<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.net/85x74/

Upvotes: 1

Ravi Gadag
Ravi Gadag

Reputation: 15861

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

Upvotes: 3

Richard Dalton
Richard Dalton

Reputation: 35793

You can do it with jQuery or without:

$('input[name="test"]').prop('checked', true);
document.getElementsByName("test")[0].checked = true;

http://jsfiddle.net/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">

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191749

You can use document.querySelector to select by attribute in any modern browser.

document.querySelector('[name=test]').checked = true;

http://jsfiddle.net/ExplosionPIlls/xpxHe/

Upvotes: 3

VisioN
VisioN

Reputation: 145398

Yes, 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.net/GKFcR/

Upvotes: 6

Related Questions