Showing posts with label drop down. Show all posts
Showing posts with label drop down. Show all posts

Saturday, March 5, 2011

Remove an option dynamically from Drop down or list using javascript and jquery

If there is a requirement to delete an existing option from a select input field in a form dynamically,  that can be a list box or combo, i.e drop down type of select. You can dynamically remove an option from it using java script or jquery using the following code snippet. The id selector is used here, if you wish you can use other selectors also. To remove an option from select, the following java script can be used,

document.getElementById('SELECT_ID').remove(option_index);

the same can be achieved using the following jquery snippet,

$("#SELECT_ID option[value='OPTION_VALUE']").remove();

For eg:- if the html code for the select is like this,

<select id='myselect'>
<option value="I loves Linux">I loves Linux</option>
<option value="I use windows too">I use windows too</option>
<option value="Linux is free software">Linux is free software</option>
<option value="Java script is simple">Java script is simple</option>
</select>

then the java script code to remove the option 'I use windows too' will be,

document.getElementById('myselect').remove(1); //it is 1 because the index start from 0

using jquery,

$("#myselect option[value='I use windows too']").remove();

Sunday, December 5, 2010

Add a new option to drop down using java script and jquery

Sometimes the developer will need to add a new option to the select (drop down/list) dynamically. You can achieve this by using java script or jquery. The below code will add a new option to the existing select input field. The id of the select is the selector used in the case, you can use other selectors too.To add a new option dynamically to drop down the following java script code can be used,

var newoption = document.createElement("OPTION");
        newoption .text = 'Option_display_text';
        newoption .value = 'Option_value';
        document.getElementById('DROPDOWN_ID').options.add(newoption );
 

same can be achieved using jquery using this snippet,

$("#DROPDOWN_ID").append('<option value="Option_value">Option_display_text</option>');

For e.g:- if the html for select (drop down) is like this,

<select id="country">
<option value="India" >India</option>
<option value="KSA" >KSA</option>
<option value="UK" >UK</option>
<option value="USA" >USA</option>
</select>

to insert a new option quatar then the javascript code will look like this,
var newoption = document.createElement("OPTION");
        newoption .text = 'quatar';
        newoption .value = 'quatar';
        document.getElementById('country').options.add(newoption );

and in jquery it is like this,


$("#country").append('<option value="Quatar">Quatar</option>');