Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery filter a select which its options contains some string

Consider below select

<select id="phone_line" name="phone_line">
    <option value=""></option>
    <option value="BB-11">Line 1</option>
    <option value="AA-22">Line 2</option>
    <option value="AA-33">Line 3</option>
    <option value="BB-44">Line 4</option>
</select>

If i want to filter the options and remove line with value BB-44 I can do it as:

$('#phone_line option').filter(' option[value="BB-44"] ').remove();

If I want to remove lines which their values starts with AA ? I can do it with each as below:

$("#phone_line > option").each(function () {    
    if (this.value.substring(0, 2) === 'AA') {
        $("#phone_line option[value='" + this.value +"']").remove();
    }
});

But can I do it with filters ( in one line ?! ). Code At:

http://jsfiddle.net/mpp4emd1/

like image 754
Alireza Fattahi Avatar asked Jan 10 '15 14:01

Alireza Fattahi


People also ask

How do you select a particular option in a select element in jQuery?

Syntax of jQuery Select Option$("selector option: selected"); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $("selector option: selected").

How do you check if any option is selected in jQuery?

Answer: Use the jQuery :selected Selector You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

How do we filter out elements using jQuery?

jQuery filter() Method The filter() method returns elements that match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned.

What is the main difference between selectors and filters in jQuery?

jQuery selector selects all elements based on the elements name given by you. jQuery filter( ) adds further detail to the selected elements by specifying the criteria of selection.


1 Answers

Using attribute starts with selector will do it

$('#phone_line option[value^="AA"]').remove();

Reference: Attribute Starts With Selector [name^="value"]

DEMO

For more complex filtering use filter(function)

$("#phone_line > option").filter(function () {    
   return this.value.substring(0, 2) === 'AA';
}).remove();
like image 135
charlietfl Avatar answered Oct 13 '22 21:10

charlietfl