You could use the Array.prototype.forEach
method to loop through your elements and set the selected
property of that element to true if its textContent
matches a specified value, like this:
const text = "6524125";
[...document.getElementsByTagName("option")].forEach(element => {
if (element.textContent === text) {
element.selected = true;
}
});
<select id="account" class="form-control" name="account">
<option value="USFSDsdfsFLIJSD656FKLLS5admFOWEJF0SOF">5265241</option>
<option value="LDSOJFksdfo52slkdfjskdfooojoijoijoj56">6524125</option>
</select>
Another method is to set the target option
element's selected
attribute manually, this prevents you from having to write more code than you need to.
In other words, you can replace ~6 lines of JavaScript with a single HTML attribute.
This is also great if you only want to set the default value for an HTML "<select>" element.
For example:
<select id="account" class="form-control" name="account">
<option value="USFSDsdfsFLIJSD656FKLLS5admFOWEJF0SOF">5265241</option>
<option value="LDSOJFksdfo52slkdfjskdfooojoijoijoj56" selected="selected">6524125</option>
</select>
UPDATE: I just saw that you included a jQuery snippet in comments section of T.J. Crowder's post.
If you are using jQuery then you can use the :contains
selector and the jQuery.fn.attr
method to select the target option and set it's selected
attribute:
$("option:contains('6524125')").attr("selected", true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<select id="account" class="form-control" name="account">
<option value="USFSDsdfsFLIJSD656FKLLS5admFOWEJF0SOF">5265241</option>
<option value="LDSOJFksdfo52slkdfjskdfooojoijoijoj56" selected="selected">6524125</option>
</select>
If you'd like to remove the selected
attributes from the target element's siblings, then you'd use the jQuery.fn.siblings
and jQuery.fn.removeAttr
methods, like this:
$("option:contains('6524125')").attr("selected", true).siblings().removeAttr("selected");
NOTE: for more information on the forEach
method, visit this link.
Good luck.