I have a form like this
<label>Select country</label>
<select name="country">
<option value="IND" selected="selected">India</option>
<option value="MY">Malaysia</option>
<option value="US">United states</option>
</select>
</label>
I want to get the value of selected country using jquery.
This is my code in jquery document block: My jquery version: jquery-1.10.1.js
alert($('select[name="country"]').find(":selected").val());
alert($('select[name="country"] option:selected').val());
I dont like to call the selector by ID or class. Thanks in advance.
I couldn't write onChange for the country select-box. I need to execute ajax request on blur of the date input field(followup_date).
$('#followup_date').change(function(e) {
if($(this).val()!='')
{
//$('.tmslot').not(this).attr('checked', false);
var slot = $(this).val();
var country_id = $('select[name="country"] option:selected').val();
My problem is I am getting undefined for country_id.
We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery. By using val() method : The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.
The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.
Use the jQuery: selected selector in combination with val () method to find the selected option value in a drop-down list.
A more direct jQuery method to the option selected would be: var selected_option = $('#mySelectBox option:selected'); Answering the question .is(':selected') is what you are looking for: $('#mySelectBox option').
Use .val()
on select
element not on selected option
:
$('select[name="country"]').on('change', function(){
alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="country">
<option value="IND" selected="selected">India</option>
<option value="MY">Malaysia</option>
<option value="US">United states</option>
</select>
As per docs,
The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of select elements, it returns null when no option is selected and an array containing the value of each selected option when there is at least one and it is possible to select more because the multiple attribute is present.
You need to simply use .val()
with select elements jquery object to get selected option value:
$('select[name="country"]').val()
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