Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Filter list box based on the combobox

I have two lists one displays cars company and the second one displays all the cars

Here is the first comboxbox ( The first option is ALL)

<select id="company">
     <option selected="true" >ALL</option>
    <option>GM</option>
    <option>Honda</option>
    <option>Ford</option>
</select>

here is my second lisbox

<select id="names" multiple="multiple" size="8">
    <option>Chevy [GM]</option>
    <option>Buick [GM]</option>
    <option>Civic [Honda]</option>
    <option>Accord [Honda]</option>
    <option>Focus [Ford]</option>
</select>

Based on the first combox selection , I should display only that car company cars in the second list . Even the second list has the car company name in brackets .. This is fixed format . Again from the the first list if user selects "ALL" I should show all the vehicles .

Could any body give me an idea to implement this or code snippet for this ?

Thanks for your help

Regards

Kiran

like image 950
Bujji Avatar asked Jan 19 '23 22:01

Bujji


1 Answers

Not all browsers allow you to hide the individual items in a drop-down list, so you need to keep a master list, and then repopulate based on that.

var names = $('#names option').clone();

$('#company').change(function() {
    var val = $(this).val();  
    $('#names').empty();
    names.filter(function(idx, el) {
        return val === 'ALL' || $(el).text().indexOf('[' + val + ']') >= 0;
    }).appendTo('#names');
});

Working demo at http://jsfiddle.net/alnitak/WsHvS/

like image 102
Alnitak Avatar answered Jan 29 '23 13:01

Alnitak