Reputation: 1002
I have some issue in my select option script, but I can not figure out, whats wrong? Sorry, I am not really a pro at jquery.
HTML
<fieldset>
<select id="sorting">
<option value="1">A-Z</option>
<option value="2">Number</option>
</select>
</fieldset>
Jquery
$(document).change(function() {
if( $("#sorting").prop("selectedIndex", 1) ) {
alert("A-Z");
}
else if( $("#sorting").prop("selectedIndex", 2) ) {
alert("Number");
}
});
My problem: Its always "A-Z" and I can not switch to "Number" by selecting number ;(.
Here is my fiddle
Upvotes: 0
Views: 592
Reputation: 171698
You are setting not getting the selected index but index is also zero based
Change to:
$(document).on('change','#sorting', function() {
var selectedIndex = this.selectedIndex;
if( selectedIndex === 0 ) {
alert("A-Z");
}
else if( selectedIndex === 1 ) {
alert("Number");
}
});
Upvotes: 2
Reputation: 1
You're setting the value in HTML property, so use the .val() in jQuery to get the value of the option.
Upvotes: 0
Reputation: 208031
Use .val()
to get the select's value:
$("#sorting").change(function() {
if ($(this).val() == 1) {
alert("A-Z");
} else if ($(this).val() == 2) {
alert("Number");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset>
<select id="sorting">
<option value="1">A-Z</option>
<option value="2">Number</option>
</select>
</fieldset>
Upvotes: 4