To get the selected option value on change from a dropdown using jQuery, the simplest way is to use the jQuery change method, jQuery find() method, and jQuery val() method.
In order to change the list of option inside your select, you can use this code bellow. when your name select named selectId. var option = $('<option></option>'). attr("value", "option value").
Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected"). text(); alert ($var);
$('select').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
....
});
You can use the jQuery find method
$('select').change(function () {
var optionSelected = $(this).find("option:selected");
var valueSelected = optionSelected.val();
var textSelected = optionSelected.text();
});
The above solution works perfectly but I choose to add the following code for them willing to get the clicked option. It allows you get the selected option even when this select value has not changed. (Tested with Mozilla only)
$('select').find('option').click(function () {
var optionSelected = $(this);
var valueSelected = optionSelected.val();
var textSelected = optionSelected.text();
});
In case anyone is using the delegated approach for their listener, use e.target
(it will refer to the select element).
$('#myform').on('change', 'select', function (e) {
var val = $(e.target).val();
var text = $(e.target).find("option:selected").text(); //only time the find is required
var name = $(e.target).attr('name');
}
JSFiddle Demo
<select id="selectId">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
$('#selectId').on('change', function () {
var selectVal = $("#selectId option:selected").val();
});
First create a select option
. After that using jquery
you can get current selected value when user change select option
value.
I find this shorter and cleaner. Besides, you can iterate through selected items if there are more than one;
$('select').on('change', function () {
var selectedValue = this.selectedOptions[0].value;
var selectedText = this.selectedOptions[0].text;
});
$('#_SelectID').change(function () {
var SelectedText = $('option:selected',this).text();
var SelectedValue = $('option:selected',this).val();
});
Another and short way to get value of selected value,
$('#selectElement').on('change',function(){
var selectedVal = $(this).val();
^^^^ ^^^^ -> presents #selectElement selected value
|
v
presents #selectElement,
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With