Reputation: 11
I'm trying to dynamically change the option of a select2 dropdown.
I've searched the forum and have managed to change the selected option, but it is only visible when clicking on the dropdown and seeing the entire list. Apologies in advance for not being the best coder.
function changeSelectOption(designSelVal) //designSelVal = 9
{
var opts = document.getElementById("design").options;
for (var opt, i = 0; opt = opts[i]; i++)
{
if (opt.value == design)
{
document.getElementById("design").selectedIndex = i;
break;
}
}
}
/* this shows as having correctly changed from value 2 to 9 */
<option value="2" >Text Only</option>
<option value="4" >Heart Arrow</option>
<option value="9" selected>Heart</option>
The visible option remains 'Text Only' and not 'Heart', it's as if the select box needs refreshing.
Upvotes: 1
Views: 112
Reputation: 1418
You are missing the if condition :
it should be
if (opt.value == designSelVal)
function changeSelectOption(designSelVal) //designSelVal = 9
{
var opts = document.getElementById("design").options;
for (var opt, i = 0; opt = opts[i]; i++) {
if (opt.value == designSelVal) {
document.getElementById("design").selectedIndex = i;
break;
}
}
}
changeSelectOption(9);
<select id="design">
<option value="2" selected>Text Only</option>
<option value="4">Heart Arrow</option>
<option value="9" >Heart</option>
</select>
Upvotes: 1