Set a check box with specific name as well as id as checked using javaScript

html, javascript

Solution

Well, as i said IDs are always unique in the DOM. So having elements with the same ID is not valid.

You can however select by the name attribute with `getElementsByName` as this selection supports multiple element. It will just create a array that you can acces through the index value. So you can just loop through all the element and check them one by one:

var elem = document.getElementsByName('myName_1');

for(var i = 0; i < elem.length; i++)
{
   elem[i].checked = true;
}

jsFiddle

Problem

In my HTML file, I want to set a check box with specific name as well as id as= `checked`. How can I acheive this..? eg: ``` <input type="checkbox" name="myName_1" id="1" value="my Value 1"> my Value 1 ``` I know `document.getElementById('id').checked = true;`, but this only checks `id`. I need to check for `id` and `name` simultaneously using `JavaScript`. Pls help. Edit: More specific: ``` if(document.getElementById(1) && document.getElementById(1).type == "checkbox" ){ document.getElementById(1).checked = true; } ``` Note: I have other elements that have same id, but different name, as well as same name, but different id. But no two have both in common.

Original source