Filter parameters by value using jQuery

I need a filter with jquery options by values, If I have:

<select class="generic-widget" id="phone_line" name="phone_line"> <option value=""></option> <option value="2">71158189</option> <option value="4">71158222</option> <option value="3">99199152</option> <option value="1">98199153</option> </select> 

In this case, I should only show options with value = "3" and value = "4".

Using:

 $('#phone_line option[value!="3"]').remove(); 

I can filter only one value, but I need to use something with x values

How can i do this? Thanks.

+6
source share
8 answers

You need a function like this:

 function removeOptions(id,array){ str='[value!=""]'; for(i=0;i<array.length;i++){ str += '[value!='+array[i]+']'; } $('#'+id+' option'+ str ).remove(); } 

If you have an array with parameters that you do not want to delete, for example:

 var myopts = [3,4]; 

you run only:

 removeOptions('phone_line', myopts); 

Hooray!

+3
source

If you are going to reuse it over and over again, creating a function is a good idea. The following is a parameter for an array of values ​​that you would like to remove:

 function removeOptions(array) { for (var i = 0; i < array.length; i++) { $('#phone_line option[value="' + array[i] + '"]').remove(); } } 

Quick demo: http://jsfiddle.net/tymeJV/Ca2hb/1/

+5
source

Well, firstly, I don’t know where #line , but it’s not in the HTML that you provided to us.

Secondly, I would use:

 $('#phone_line option[value!=3][value!=5]').remove(); 

It is possible to have 2 conditions in one selector!

+2
source

try

 $("select[id*='line']").find('option[value!=3], option[value!=5]').remove(); or $("select[id*='line']").children('option[value!=3], option[value!=5]').remove(); 

Thanks,

+1
source
 $('#phone_line option').filter(function(){ return (this.value != 3 && this.value != 4); }).remove(); 

Fiddle

+1
source

If you want to show only parameters with values ​​3 and 4. It can simply be done with.

 $('#phone_line option').not('option[value="3"],option[value="4"]').remove(); 

Here is a demon.

or you can use filter to avoid parameter values ​​with 4 and 3

 $('#phone_line option').filter('option[value="3"],option[value="4"] ').remove(); 

Here is a demon.

+1
source

try it

 $('#line option[value!=3],option[value!=4]').remove(); 
0
source
 $('#line').find('option[value!=3], option[value!=5]').remove(); 

If the parameters are direct children, use .children () instead of .find ()

0
source

Source: https://habr.com/ru/post/945587/


All Articles