Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use jquery to remove option from select box

Tags:

jquery

How to use jquery to delete opt1 row ? How about changing opt2 to become selected? Note that the values are random numbers.

      <select name="ShippingMethod" >
        <option value="8247(random)">Opt2</option>
        <option value="1939(random)" selected="selected">Opt1</option>
      </select>
like image 982
Tom Avatar asked Nov 30 '10 12:11

Tom


People also ask

How do I remove specific option from select?

The option to be removed is selected by getting the select box. The value to be removed is specified on the value selector (value='optionValue') on the select box. The remove() method is then used to remove this selected option. The find() method can be used to find the option in the value with the value selector.

How add and remove select option in jQuery?

The remove() method removes the options, the end() takes the object back to the beginning of the script, and the append() method adds new options in the list.

Which jQuery method removes the selected item?

To remove elements and content, there are mainly two jQuery methods: remove() - Removes the selected element (and its child elements) empty() - Removes the child elements from the selected element.

How do you remove all options from select in jQuery except first?

If we want to remove all items from dropdown except the first item then we can use $('#ddlItems option:not(:first)'). remove(); Here we have excluded first item from being deleted. If we want to remove all items from dropdown except the last item then we can use $('#ddlItems option:not(:last)').


2 Answers

It depends how you want to select it, to remove by text:

$("select[name=ShippingMethod] option").filter(function() { 
    return this.text == "Opt1"; 
}).remove();

Or the selected one:

$("select[name=ShippingMethod] option:selected").remove();

Or the second one:

$("select[name=ShippingMethod] option:eq(1)").remove();

Or the last one:

$("select[name=ShippingMethod] option:last").remove();

To just select option 2 by text, you can use the same .filter() approach above:

$("select[name=ShippingMethod] option").filter(function() { 
    return this.text == "Opt2"; 
}).attr("selected", true);

You can test it here.

like image 160
Nick Craver Avatar answered Oct 05 '22 02:10

Nick Craver


Quick guess as to question two

$('select[name=ShippingMethod]').val('19395ss');

Nick Carver seems to have answered the first question.

like image 34
El Yobo Avatar answered Oct 05 '22 03:10

El Yobo