Reputation: 591
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>
Upvotes: 1
Views: 3075
Reputation: 6156
$('#strings option[value=Test]').attr('selected', true);
Demo Jsfiddle with similar ids
Upvotes: 0
Reputation: 6180
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";
Upvotes: 1
Reputation: 28837
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:
Upvotes: 3