Naourass Derouichi
Naourass Derouichi

Reputation: 793

Programmatically select dropdown option

Is it possible to fire option click programmatically with pure Javascript?

HTML:

<select id="racetype" class="select-menu" name="race-type">
            <option value="value" class="select-option js-select-option racetype-all" data-filter-value=".js-find-race-item">Race Types</option>
            <option value="value" class="select-option js-select-option racetype-sprint" data-filter-value=".js-type-sprint">Sprint</option>
            <option value="value" class="select-option js-select-option racetype-super" data-filter-value=".js-type-super">Super</option>
            <option value="value" class="select-option js-select-option racetype-beast" data-filter-value=".js-type-beast">Beast</option>
</select>

<a href="javascript:void(0)" onclick="SOsprint();">Click to select the second option (Sprint)</a>

JAVASCRIPT:

function SOsprint() {
    var select = document.getElementById("racetype");
    select.selectedIndex = 1;
    return false;
}

Upvotes: 0

Views: 2239

Answers (2)

Satpal
Satpal

Reputation: 133453

There is no need to use [0] as document.getElementById returns a reference to the element by its ID not an array.

Use

 var select = document.getElementById("racetype");

instead of

var select = document.getElementById("racetype")[0];

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59292

You don't need [0]. getElementById() returns just a single element and not a NodeList

Do this:

var select = document.getElementById("racetype");

Upvotes: 1

Related Questions