简体   繁体   中英

Setting dropdown values in Javascript

I have a dropdown with following HTML.

<select name="custom_123" id="custom_123_123" class="custom form-control form-control-full form-select searchable  abcd-done" style="display: none;">
<option value="" selected="selected">None</option>
<option value="1">Alaska</option>
<option value="2">Newyork</option>
</select>
<div id="custom_123_123_abcd" class="abcd-container abcd-container-single abcd-container- 
active" style="width: 100%"><a href="javascript:void(0)" class="abcd-single" 
tabindex="-1"><span>Alaska</span></a>
</div>

I want to be able to select Newyork in the dropdown. For that, I am during the following.

var dropdown_id = document.querySelector('[id^="custom_123"]').id;
var dropdown_abcd = dropdown_id + 'abcd';
document.getElementById(dropdown_abcd).getElementsByClassName("abcd-single")[0].innerHTML = "Alaska";

But the same doesn't get applied. Can anyone help?

Here is an example based on your code:

const select = document.querySelector('[id^="custom_123"]');
select.value = 'Alaska';

Update on comment
If there are listeners on the select, here is an example on how to fire a change event.

const select = document.querySelector('[id^="custom_123"]');
select.value = 'Alaska';
select.dispatchEvent(new CustomEvent('change'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM