I bound an event on the change event of my select elements with this:
$('select').on('change', '', function (e) {
});
How can I access the element which got selected when the change event occurs?
I bound an event on the change event of my select elements with this:
$('select').on('change', '', function (e) {
});
How can I access the element which got selected when the change event occurs?
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');
}
<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.
See official API documentation https://api.jquery.com/selected-selector/
This good works:
$( "select" ).on('change',function() {
var str = "";
// For multiple choice
$( "select option:selected" ).each(function() {
str += $( this ).val() + " ";
});
});
and
$( "select" ).on('change',function() {
// For unique choice
var selVal = $( "select option:selected" ).val();
});
and be easy for unique choice
var SelVal = $( "#idSelect option:selected" ).val();
You can use this jquery select change event for get selected option value
$(document).ready(function () {
$('body').on('change','#select', function() {
$('#show_selected').val(this.value);
});
});
<!DOCTYPE html>
<html>
<title>Learn Jquery value Method</title>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<select id="select">
<option value="">Select One</option>
<option value="PHP">PHP</option>
<option value="jAVA">JAVA</option>
<option value="Jquery">jQuery</option>
<option value="Python">Python</option>
<option value="Mysql">Mysql</option>
</select>
<br><br>
<input type="text" id="show_selected">
</body>
</html>