Pepe
Pepe

Reputation: 1002

Do something on select option switch

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

Answers (3)

charlietfl
charlietfl

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

Gabriel Consalter
Gabriel Consalter

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

j08691
j08691

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

Related Questions