john
john

Reputation: 707

How to get selected option from "select" tag on mobile browser?

I need to get the selected value from the following drop down list

<select id = "sel123">
  <option selected value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select> 

Here is what I try

 alert($("#sel123 option:selected").text()); 

I works fine on desktop browser.

But when I test the same thing on mobile device, the jqueryALWAYS pulls the "Volvo" option no matter what I choose . What i mean is when I select "Saab", or "Audi" the drop down shows "Saab", or "Audi" . . . but the jquery alert still shows "Volvo"

Why is it happening? How to get the "selected" value on a mobile browser? (I have been testing it on Airwatch browser IPhone and Chrom Android)

EDIT: I suspect this might be because I have selected attr preset within the "Volvo" option and the mobile browser is not identifying the change

Upvotes: 2

Views: 2047

Answers (2)

charlietfl
charlietfl

Reputation: 171700

Lets try removing the selected attribute as soon as any change occurs

$("#sel123").change(function() {
  $(this).find("option[selected]").removeAttr('selected');
});

Upvotes: 0

caramba
caramba

Reputation: 22490

You need to alert if a change happens. Try like so:

$("#sel123").change(function() {
  alert($(this).find("option:selected").text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id = "sel123">
  <option selected value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

read more about jQuery change() here

Upvotes: 2

Related Questions