Thampuran
Thampuran

Reputation: 654

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

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.

Upvotes: 3

Views: 3283

Answers (4)

Maple
Maple

Reputation: 741

As mentioned by several comments, it is not valid to have more than one element with the same id. If there are more than one of the same id, the behavior is unreliable. If you have groupings of elements that are similar, a common convention with many developers is to give them a common class. This could/would replace your use of name. You can then search on elements within a certain class that have a specific id. (Which may be redundant, depending on your use.)

Searching by class is done with document.getElementsByClassName("myClass"), which returns an array of elements, similar to getElementsByName. Once you have this array, you can then loop through to determine if your id is within that class group[see note below] and apply effects as necessary. (e.g. elementArray[i].checked = true)

Note - It would be much more efficient to search for the id then determine the class, in my opinion.

Upvotes: 1

nkmol
nkmol

Reputation: 8091

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

Upvotes: 4

Jason
Jason

Reputation: 1959

You could do something like this, not ideal, but would solve the problem.

var names = document.getElementsByName(nameToFind);
names.forEach(funciton(item) {
  if (item.id == idToFind)
    item.checked = true;
});

Upvotes: 2

Bud Damyanov
Bud Damyanov

Reputation: 31839

Having id of HTML elements, starting with a number is incorrect. Rename your id and make it unique. Also value of id of 1 evaluates to true by javascript engine. However if your HTML document is HTML5 compliant then id starting with a number is not problem.

Upvotes: 1

Related Questions