6

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.

chandoo
  • 1,276
  • 2
  • 21
  • 32

4 Answers4

11

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>
Timur Osadchiy
  • 5,699
  • 2
  • 26
  • 28
  • Tim, thanks a lot for your time. But, I couldn't write onChange for the select-box. I need to execute ajax request on blur of the input field. – chandoo Mar 31 '15 at 10:33
  • 1
    @chandoo Always welcome! Please feel free to mark my answer as accepted:) `on('cahnge')` here is just for example to demonstrate the main idea - use `$('select[name="country"]').val()` for getting the value of `select` element. – Timur Osadchiy Mar 31 '15 at 10:49
5

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()
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
3

if you want to get the option:

alert($('select[name=country]').find(':selected').text());

ShirleyCC
  • 775
  • 9
  • 8
2

You may need this Demo Here

alert($('select[name="country"]').val());
$('select[name="country"]').change(function(){    
    alert($(this).val());    
});
I'm Geeker
  • 4,601
  • 5
  • 22
  • 41