You can use the HTMLSelectElement.selectedIndex
property to set the index of the selected option.
If you set it to 0
, it will select the first option .
You can add option
to select
using HTMLSelectElement.add()
. The correct syntax (from the docs):
collection.add (item [, before]);
Elementis an HTMLOptionElement or HTMLOptGroupElement element
before that, an element of the collection, or an index of the long type representing the item of goods, must be inserted earlier. If this parameter is null (or the index does not exist), the new element is attached to the end of the collection.
You used three arguments, not two .
So, one of the possible approaches is possible:
btn1.onclick = function(){ x.add(option, 0 );
Working demo: https://jsfiddle.net/mrlew/w1zqL0h9/
As said, if you pass null
as the second argument, it will add your option
to the end. And you can select it by passing length-1
to selectedIndex
.
btn1.onclick = function(){ x.add(option, null);
mrlew source share