john doe
john doe

Reputation: 9660

Set the Selected Attribute on the Selected Option in jQuery

I have the following implementation which triggers the change event whenever I change the select values.

 $(element).on("change", function() {



            });

Now, inside the on change function I need to get the option that is selected and then attach the selected = selected attribute to it.

So I can get the value using the following:

  $(element).on("change", function() {

                alert($(this).find(":selected").text());

            });

But the selected value is not reflected in the user interface. It still shows no selection.

Upvotes: 0

Views: 1842

Answers (3)

Giannis Grivas
Giannis Grivas

Reputation: 3412

To get selected option value:

$(element).on("change", function() {
  var item=$(this);
  alert(item.val())
});

or

$(element).change(function() { 
  var item=$(this);
  alert(item.val())
});

fiddle to play.

var element = $("#options");

$(element).on("change", function() {
  var item=$(this);
  alert(item.val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="options">
  <option value="select">Select</option>
  <option value="select 1 value">Select 1</option>
  <option value="select 2 value">Select 2</option>
</select>
The way to get the selected dropdown value on change:

Upvotes: 1

Johan Karlsson
Johan Karlsson

Reputation: 6476

Try this:

 $("#select").on("change", function() {
     $(this.selectedOptions[0]).attr("selected", "selected");
 });

Upvotes: 0

Ricardo Teixeira
Ricardo Teixeira

Reputation: 1

Inside that function: $(this).find(':selected').attr('selected', 'selected') ;

That will do it. But why do you need it? You can get the selected option with the :selected pseudo selector.

http://api.jquery.com/selected-selector/

Upvotes: 0

Related Questions