Bigboymanted
Bigboymanted

Reputation: 43

Javascript, auto select a drop down menu

So What I am trying to do with Javascript, is make it so when I do something similar to document.getElementByID("product-select").value = "34"; It will automatically press it for me.

Whenever I try to do this what it does is it makes the drop down menu go blank and It wont change it automatically. Can I have some help ?

<div id="product-variants" class="">
  <div class="select-wrapper">
    <select id="product-select" name="id" class="">




      <option value="28223706565">32</option>



      <option value="28223706629">34</option>



      <option value="28223706693">36</option>


    </select>
  </div>
</div>

Upvotes: 3

Views: 23835

Answers (3)

Nishesh Pratap Singh
Nishesh Pratap Singh

Reputation: 2181

Reason for why drop down value is not changing automatically is, When you are setting value of drop down using document.getElementByID("product-select").value = "34", it will not select option with text node as 34, this will change the dropdown only when one of your options has value of 34. In order to make it work you can change your implementation as show below :

var options = document.getElementById("product-select").options;
for (var i = 0; i < options.length; i++) {
  if (options[i].text == "34") {
    options[i].selected = true;
    break;
  }
}

Upvotes: 6

Quartal
Quartal

Reputation: 410

If you know the order of your values you can use the

document.getElementByID("product-select").selectedIndex method

If you want to choose the value 34 in this case it is the second option so its index is 1, 32 index would be 0 and 36 index would be 2

So if you want to change the value to 34 you call

document.getElementByID("product-select").selectedIndex = 1

Upvotes: 1

Tim D
Tim D

Reputation: 690

Perhaps

document.getElementByID("product-select").value = "34";

should be

document.getElementByID("product-select").value = "28223706629";

Another approach is to refer to the index such as

document.getElementById("product-select").selectedIndex = 1;

Upvotes: 2

Related Questions