Skip to main content

Working with select or drop-down using jQuery

In this article we are going to learn some operation on the select box using jQuery as below.

1. Add new option to a select-element with jQuery


<select id="ddlStatus"></select>

<script type="text/javascript" language="javascript" >
var status = new Array();

status.push("<option value=\"In Process\">In Process</option>");
status.push("<option value=\"On Hold\">On Hold</option>");

$("#ddlStatus").html(status.join(''));

</script>

2. Retrieve the selected single value from the select box with jQuery


$('#ddlStatus').val();

3. Retrieve the multiple selected value from the select box with jQuery


$('#ddlStatus option:selected').each(function(counter, option){
console.log($(option).val());
});

4. Sometime if you don’t want to retrieve selected value and want to get selected text then use the below code


$('#ddlStatus option:selected').text();

5. Retrieve the multiple selected text from the select box with jQuery

If you have a multiple choice element you should go with this code:

$('#ddlStatus option:selected').each(function(counter, option){
console.log($(option).text());
});

6. If you want to remove a specific option from the select box using jQuery

Below code will remove the option which has the value = 2 from the using jQuery


$('#ddlStatus option[value=2]').remove();

7. Clear a selectbox using jQuery

$('#ddlStatus').html('');

hope this will help someone 🙂

Tarun Dudhatra

Tarun is a writer of http://www.codingsharp.com website. He is a software professional with hands on 10+ years of experience. Generally he writes an article about microsoft technology, Javascript, SQL Server and JQuery. Here he shares his notes, experiences, examples.