Working with select tag and option in HTML using JQuery

JQuery made it really simple working with HTML select control. Consider you have following select control and you want to do various operations as listed thereafter.

<select id="selectCtrl" multiple="multiple">
    <option value="bb">Black Berry</option>
</select>


The attribute multiple=“multiple” will make this select as multi select.

1. How to add a new option to a HTML select control

$('#selectCtrl').append('<option value="ga">Green Apple</option>');
$('#selectCtrl').append('<option value="ym">Yellow Mango</option>');


2. How to get all the selected option ids from a HTML select control

var selectedIds = $('#selectCtrl').val();

This will return an array of all the selected ids.


3. How to get all the selected option display text from a HTML select control

var all = $('#selectCtrl option:selected').map(function(){
    return $(this).text();
}).get();

This will return an array of all the selected display texts.


4. How to get all options irrespective selection from HTML select control

var all = $('#selectCtrl option').map(function(){
    return $(this).val();
}).get();

This will return an array of all the available ids irrespective selection. We can replace .val() with .text() to get all the display texts as an array.


5. How to remove all selected options from HTML select control

$('#selectCtrl option:selected').remove();


6. How to remove all options from HTML select control

$('#selectCtrl option').remove();


Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus