Neil
Neil

Reputation: 111

Is it possible to trigger JavaScript when a user selects the current option in an HTML select?

I know that you can use the onchange event on the select to trigger a JavaScript function, but what if they choose the option that is currently selected?

The reason for this is I want to have a drop down list of a bunch of websites. This is used as a sort of jumppage, if you will. When the user selects a site the selected site opens in a new window. Now if they close the new tab/window the select is on the last option they selected. If the user wants to go to the same website again the onchange event does not fire.

I know that you can change the select option back to the default option with a null value like this:

html

<select onChange="jsFunction(this.value)" id="selectOpt">
    <option value="">1</option>
    <option value="websiteURL2">2</option>
    <option value="websiteURL3">3</option>
</select>

javascript

function jsFunction(opt){
    window.location = opt;
    document.getElementById("selectOpt").options[0].selected = true;
}

http://jsfiddle.net/XqLmY/1/

But I was wondering if it could be done without that.

Can I trigger an event using a HTML select without changing its value?

Upvotes: 1

Views: 315

Answers (2)

Neil
Neil

Reputation: 111

Not really an answer, but I just ended up using this method because it was easy and didn't have other dependencies.

function jsFunction(opt){
    window.location = opt;
    document.getElementById("selectOpt").options[0].selected = true;
}

Upvotes: 0

szydan
szydan

Reputation: 2596

What about using onClick instead Look here http://jsfiddle.net/9X4Ks/1/

<select onclick="clickFunction(this)" id="selectOpt">
    <option value="websiteURL1">1</option>
    <option value="websiteURL2">2</option>
    <option value="websiteURL3">3</option>
</select>

function clickFunction(o){
    alert(o.value)
}

It fires even when user clicks the selected option second time.
Unfortunately it works only in chrome and opera. Does not work in firefox

Upvotes: 0

Related Questions