-1

How can I use javascript, to automatically select Option value 2? But I have and as the same id ..

var index = 1; /* option do select*/
document.getElementById("594951-Cor").options.selectedIndex = index;
<div id="594951-Cor" name="594951-Cor">

<select id="594951-Cor" name="594951-Cor" class="">
<option value="0">Selecione...</option>
<option value="1">Color 01</option>
<option value="2">Color 02</option>
</select>

</div>
  • 1
    You have 2 elements with the same ID, and the `document.getElementById` returns the first. That is not a valid HTML! https://stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same-id-if-theyre-different-eleme – Manuel Romeiro Dec 10 '21 at 00:54

1 Answers1

0

After solve the problem with ID's (change the duplicated id's), if you want to select by value, just assign on the select node:

document.getElementById("594951-Cor").value = "2";

assuming that you want to select <option value="2">Color 02</option> and the id of the select node is "594951-Cor".

The "2" is the value of the `option, not the index.

Manuel Romeiro
  • 1,002
  • 12
  • 14
  • I can't change the div id, because I use a shopify theme and I can't access the code, for that reason I would like to develop the code in javascript. Because this change via html is easier. is there a way to select only the id of the select? – Kleuton Novais Dec 10 '21 at 11:07
  • If the structure will be always that (DIV and then SELECT), you can use `document.getElementById("594951-Cor").children[0]` to get the `SELECT` node. Other alternative is to use `document.querySelector("select#594951-Cor")`, but will not work since the ID must start with letter. – Manuel Romeiro Dec 10 '21 at 12:04