Reputation: 134
Using vanilla JavaScript I am trying to change the default option of a select box.
var temp = "Approve";
var mySelect = document.querySelector('[id^="select_leave_action_"]').id;
for(var i, j = 0; i = mySelect.options[j]; j++) {
if(i.value == temp) {
mySelect.selectedIndex = j;
break;
}
}
When I execute the above code I get the following error:
Uncaught TypeError: Cannot read property '0' of undefined at :4:39`
What is wrong with my code?
I tried to use getElementsByClassName
instead of querySelector
, but still have the same problem.
Upvotes: 0
Views: 138
Reputation: 29072
Remove .id
.
The ID is a string and won't have an options
property. You want to store the select element itself (not its ID) to access its options.
(Also it's even simpler to just set mySelect.value = temp
, the only difference to your current method will be how the case is handled where temp
is not existing in the options that exist. Depending on the browser, setting the value directly may display the box empty if no fitting option exists.)
Upvotes: 1