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>
Boaz
  • 19,892
  • 8
  • 62
  • 70
user2492064
  • 591
  • 1
  • 8
  • 21
  • 5
    You must have unique IDs, not same id for different elements – Sergio Sep 07 '13 at 09: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! – Chamila Chulatunga Sep 07 '13 at 09:48
  • Also, your `getElementById()` call is passed a different ID than the one the DOM elements have. – Boaz Sep 07 '13 at 09:48
  • Try jQuery, put a `class` of `dropdown_test` to the ` – PurkkaKoodari Sep 07 '13 at 09:49

3 Answers3

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:

Community
  • 1
  • 1
Sergio
  • 28,539
  • 11
  • 85
  • 132
  • +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. – Boaz Sep 07 '13 at 09:52
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";
Boaz
  • 19,892
  • 8
  • 62
  • 70
sudhansu63
  • 6,025
  • 4
  • 39
  • 52
0
$('#strings option[value=Test]').attr('selected', true);

Demo Jsfiddle with similar ids

Vaibs_Cool
  • 6,126
  • 5
  • 28
  • 61