0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rekha R
  • 131
  • 1
  • 1
  • 12
  • Does this answer your question? [How do I programmatically set the value of a select box element using JavaScript?](https://stackoverflow.com/questions/78932/how-do-i-programmatically-set-the-value-of-a-select-box-element-using-javascript) – smartdroid Nov 24 '20 at 06:21
  • No. I check it before and it seemed similar, but solution doesnt work for me for some reason. – Rekha R Nov 24 '20 at 06:40
  • Have you tried the solution in the accepted answer on the link? That is the right way to set a select value. So if it’s not working, there is something wrong in somewhere else in your code. Did you get an error? – smartdroid Nov 25 '20 at 08:14

1 Answers1

1

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'));
erosman
  • 7,094
  • 7
  • 27
  • 46
  • I tried this as well and doesnt work. The text reflects on the page, but when the browser makes the ajax call, it doesnt pick this value – Rekha R Nov 24 '20 at 06:38
  • @RekhaR The answer was based on your question. The ajax call has to be check to see where it gets it data. I will add an alternative but it is a general idea and may need to be adjusted. – erosman Nov 24 '20 at 07:01