Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter options by value with Jquery

Tags:

jquery

I want filter with jquery the 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>

For this case I must show the options with value="3" and value="4" only.

Using:

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

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

How can I do that? Thanks.

like image 384
Goku Avatar asked May 22 '13 12:05

Goku


4 Answers

If you're going to be re-using this over and over again, creating a function is a good idea. The below takes an array parameter of values you would like to remove:

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

A quick demo: http://jsfiddle.net/tymeJV/Ca2hb/1/

like image 166
tymeJV Avatar answered Nov 14 '22 22:11

tymeJV


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 a array with the options that you don't want remove, like this:

var myopts = [3,4];

you only run:

removeOptions('phone_line', myopts);

Cheers!

like image 45
chespinoza Avatar answered Nov 14 '22 23:11

chespinoza


Well first, i don't know where is #line but it is not in the HTML you provided us.

Second I would use :

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

It is possible to have 2 condition in one selector!

like image 28
Karl-André Gagnon Avatar answered Nov 15 '22 00:11

Karl-André Gagnon


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,

like image 30
SivaRajini Avatar answered Nov 14 '22 22:11

SivaRajini