I have list select:
<select id="sel">
<option id="a1" value="volvo">Volvo</option>
<option id="a2" value="saab">Saab</option>
<option id="a3" value="mercedes">Mercedes</option>
<option id="a4" value="audi">Audi</option>
<option id="a5" value="volvo2">Volvo2</option>
<option id="a6" value="saab2">Saab2</option>
<option id="a7" value="mercedes2">Mercedes2</option>
<option id="a8" value="audi2">Audi2</option>
</select>
and in PHP i have array:
$array = array('a1', 'a4', 'a5', 'a8');
How to with jQuery show in select #sel only values where id option is isset in $array of PHP?
For this example should be:
<select id="sel">
<option id="a1" value="volvo">Volvo</option>
<option id="a4" value="audi">Audi</option>
<option id="a5" value="volvo2">Volvo2</option>
<option id="a8" value="audi2">Audi2</option>
</select>
I dont want use PHP for this. I would like use jQuery. Thanks!
Using the php array you can generate the selector like this and remove or hide unwanted options.
You can render the array or selector('#a1, #a4, #a5, #a8'
) itself from server side and use it on the client side.
$('select option').not('#a1, #a4, #a5, #a8').remove();
If its an array you can try this.
$('select option').not('#' + array.join(',#')).remove();
Working demo - http://jsfiddle.net/TZCcA/1/
You can do this but you'll need to echo your PHP array to the page so that jQuery can use it.
jQuery:
var ary = ['a1', 'a4', 'a5', 'a8']; // output your PHP array here
$('option').each(function() {
if ($.inArray($(this).attr('id'), ary)==-1) $(this).remove();
})
And you'd want to echo your PHP array in the jQuery array definition. Something like this:
var ary = [
<?php
foreach($item in $array){
echo "'$item',";
}
?>
];
Note that this will add an extra comma at the end which you do not want. Removing that with a loop is trivial however I did not add that to this code.
jsFiddle example (without the PHP).
You would first need to spit your array out into a usable format so that jQuery can access its values. I would suggest using json_encode for this.
echo json_encode( array('a1', 'a4', 'a5', 'a8') );
The output will be:
["a1","a4","a5","a8"]
So it's best if you assign that to a variable. Following that, you would cycle through your list and hide any elements not found within your array:
// Our array from PHP
var myArr = ["a1","a4","a5","a8"];
// Select all options, and filter
$("#sel option").filter(function(){
// Return items not found in our array
return $.inArray( this.id, myArr ) === -1;
}).remove();
Working demo at: http://jsbin.com/ocebup/edit#javascript,html
ShankarSongoli had a great solution as well, which doesn't require a filter, but rather modifies the array of values into a selector and passes it into the $.not() method. See their answer for the code: https://stackoverflow.com/a/9723034/54680