Reputation: 9660
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
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())
});
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>
Upvotes: 1
Reputation: 6476
Try this:
$("#select").on("change", function() {
$(this.selectedOptions[0]).attr("selected", "selected");
});
Upvotes: 0
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