Sunday, March 23, 2014

[jQuery][Tutorial] Get select value from dropdown list with example.

This is the sample of the drop down list:
<select id="dropdownlist">   
<option value=’car 1’>Option 1</option>
   
<option value=’car 2’>Option 2</option>
   
<option value=’car 3’>Option 3</option>
    
<option value=’car 4’>Option 4</option>    
<option value=’car 5’>Option 5</option>
<select> 
Text in pink is id name you named to the drop down list, you can rename that to any name. Text in blue is value and text in orange is the text shown to user.

And use these code can get the option value by using this sentence:
$('#dropdownlist option:selected').val();
And use these code can get the option text:
$('#dropdownlist option:selected').text();

For an example:
    $('#dropdownlist').change(function() {    
    var option_val = $('#dropdownlist option:selected').val ();
    alert(option_val);
    });

$('#dropdownlist').change(function() {});
<- This is for detect if the dropdown list is changed by user, run event :

var option_val = $('#dropdownlist option:selected').text();
<- and this is for getting the text value from the selected option and store in a value named option_val.

Full set of code as an example to get value:
<html>
<head>
<title>jQuery get select value from dropdown</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<script>
$( document ).ready(function() {
    $('#dropdownlist').change(function() {   
    var option_val = $('#dropdownlist option:selected').val();
    alert(option_val);    });
});
</script>

<select id="dropdownlist">
    <option value='car 1'>Option 1</option>
    <option value='car 2'>Option 2</option>
    <option value='car 3'>Option 3</option>
    <option value='car 4'>Option 4</option>
    <option value='car 5'>Option 5</option>
</select>
</body>
</html>

When you view the webpage in browser, you will see the drop down list,
Try selecting option 5:


And then will pop up the alert box with the selected value:



 
Full set of code as an example to get option text shown to user:
<html>
<head>
<title>jQuery get select value from dropdown</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<script>$( document ).ready(function() {
    $('#dropdownlist').change(function() {
    var option_text = $('#dropdownlist option:selected').text();
    alert(option_text);    });
});
</script>
<select id="dropdownlist">
    <option value='car 1'>Option 1</option>
    <option value='car 2'>Option 2</option>
    <option value='car 3'>Option 3</option>
    <option value='car 4'>Option 4</option>
    <option value='car 5'>Option 5</option>
</select>
</body>
</html>




Reference:
https://learn.jquery.com/using-jquery-core/faq/how-do-i-get-the-text-value-of-a-selected-option/

No comments :

Post a Comment