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/
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").
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With