Hello friends this is my code:
Try this :
$('#input_id :selected').val(); //for getting value from selected option
$('#input_id :selected').text(); //for getting text from selected option
Other answers wasn't working for me so i developed solution:
I created option with class="option-item" for easy targeting
HTML :
<select id="select-test">
<option value="5-val" id="first-id" class="option-item"> First option </option>
</select>
Then for every selected option i added display none property
CSS:
option:checked {
display: none;
}
Now we can add change to our SelectBox to find our selected option with display none property by simple :hidden attribute
JQuery:
$('#select-test').change(function(){
//value
$('#select-test').find('.option-item:hidden').val();
//id
$('#select-test').find('.option-item:hidden').attr('id');
//text
$('#select-test').find('.option-item:hidden').text();
});
Working fiddle: https://jsfiddle.net/Friiz/2dk4003j/10/
This solution allows you to forget select element. Helpful when you do not have an id on select elements.
$("#first").select2()
.on("select2:select", function (e) {
var selected_element = $(e.currentTarget);
var select_val = selected_element.val();
});
$("#first").select2('data') will return all data as map
If you are using ajax, you may want to get updated value of select right after the selection.
//Part 1
$(".element").select2(/*Your code*/)
//Part 2 - continued
$(".element").on("select2:select", function (e) {
var select_val = $(e.currentTarget).val();
console.log(select_val)
});
Credits: Steven-Johnston
Simple answer is :
$('#first').select2().val()
and you can write by this way also:
$('#first').val()