1

I am trying to use JS to update the selected value of multiple select elements, at the same time. For some reason, my JS only updates one select, not all of them on the page. Unfortunately, I am not able to change the id attribute of the select, and the various select elements need to have the same id.

How might I change the function so that ALL drop downs with id 'dropdown-test' are updated?

JS

document.getElementById('dropdown-test').value="3";

HTML

<select id="dropdown_test">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>

<select id="dropdown_test">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
4
  • 5
    You must have unique IDs, not same id for different elements Commented Sep 7, 2013 at 9:45
  • 1
    "the various selects need to have the same id." - if this is true, you have a requirement that means you'll be doing HTML all wrong. The whole point of Id's is that they are unique within a page! Commented Sep 7, 2013 at 9:48
  • Also, your getElementById() call is passed a different ID than the one the DOM elements have. Commented Sep 7, 2013 at 9:48
  • Try jQuery, put a class of dropdown_test to the <select>s and use $(".dropdown_test").val(3) Commented Sep 7, 2013 at 9:49

3 Answers 3

3

You must have unique IDs. If you want to use jQuery you can do like this:

$('select').val(3);

Demo here

If you want to use plain javascript you can use:

var all_select = document.getElementsByTagName("select");
for (i = 0; i < all_select.length; i++) {
    all_select[i].value = 3;
}

Demo here

If you need ids anyway, please give them different names.

Read about ID:

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Note though the OP specifically says the only constraint is that the id cannot be changed and must be the same for all elements, even though that is invalid.
1

try using class name.Id should be unique.

HTML

<select class="dropdown_test">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>

<select class="dropdown_test">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>

JS

document.getElementByClass('.dropdown-test').value="3";

Comments

0
$('#strings option[value=Test]').attr('selected', true);

Demo Jsfiddle with similar ids

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.