Stargazer
Stargazer

Reputation: 1530

onChange not working

I am working with a jquery dropdown menu. It is almost done, but for some reason I can't get the onChange working.

<select id="cd-dropdown" class="cd-select" ONCHANGE="location = this.options[this.selectedIndex].value;" >
    <option value="-1" selected>Selecione uma categoria</option>
    <option value="1" class="icon-google-plus">Massa Muscular</option>
    <option value="2" class="icon-facebook">Resistência</option>
    <option value="http://www.google.com" class="icon-twitter" >Vitaminas</option>
    <option value="4" class="icon-github">Emagrecimento</option>
</select>

Upvotes: 0

Views: 589

Answers (3)

Andrew Brown
Andrew Brown

Reputation: 5424

HTML:

<select id="cd-dropdown">
    <option disabled selected>Select</option>
    <option value="http://www.facebook.com">Facebook</option>
    <option value="http://www.google.com">Google</option>
</select>

Jquery:

$("#cd-dropdown").on('change', function(){
    var url = $("option:selected", this).val();
    window.location = url;
});

Whenever a new value is assigned to the location object, a document will be loaded using the URL as if window.location.assign() had been called with the modified URL.

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167240

Use location.href:

<select id="cd-dropdown" class="cd-select"
        ONCHANGE="location.href = this.options[this.selectedIndex].value;" >
------------------^

Explanation

The keyword location is the Object. The href property of the location object says the URL.

Full Code:

<select id="cd-dropdown" class="cd-select" ONCHANGE="location.href = this.options[this.selectedIndex].value;" >
    <option value="-1" selected>Selecione uma categoria</option>
    <option value="1" class="icon-google-plus">Massa Muscular</option>
    <option value="2" class="icon-facebook">Resistência</option>
    <option value="http://www.google.com" class="icon-twitter" >Vitaminas</option>
    <option value="4" class="icon-github">Emagrecimento</option>
</select>

Upvotes: 1

jacouh
jacouh

Reputation: 8769

I would prefer this simpler code:

onchange="location.href = this.value;"

Here this is the select object.

Your code here:

<select id="cd-dropdown" class="cd-select" onchange="location.href = this.value;" >
    <option value="-1" selected>Selecione uma categoria</option>
    <option value="1" class="icon-google-plus">Massa Muscular</option>
    <option value="2" class="icon-facebook">Resistência</option>
    <option value="http://www.google.com" class="icon-twitter" >Vitaminas</option>
    <option value="4" class="icon-github">Emagrecimento</option>
</select>

Upvotes: 0

Related Questions