Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter values in Multiple selection using textbox value

I have a text box and multiple selection box. When ever I write something in text box it will filter that text in the multiple selection and show only matched value.

<!DOCTYPE html>
<html>

<body>
    <select id="uniqueCarNames" name="cars" multiple>
        <option value="volvo">Long Distance Travel</option>
        <option value="saab">Amazing </option>
        <option value="opel">Excellent Travelling</option>
        <option value="audi">I am rich</option>
    </select>
    <input type="text" id="filterMultipleSelection" />
</body>

</html>

So if I start writing in input box it will start filtering the values in selection box. I want the filtering using text of option tag. Please guide.

like image 616
s_k_t Avatar asked Aug 31 '26 17:08

s_k_t


1 Answers

The .filter(function) jQuery method can be used to find the target option elements and show them as follows. The JavaScript method .toLowerCase() is used to make the search case-insensitive:

$('#filterMultipleSelection').on('input', function() {
    var val = this.value.toLowerCase();
    $('#uniqueCarNames > option').hide()
    .filter(function() {
        return this.value.toLowerCase().indexOf( val ) > -1;
    })
    .show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id="uniqueCarNames" name="cars" multiple>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="opel">Opel</option>
        <option value="audi">Audi</option>
    </select>
    <input type="text" id="filterMultipleSelection" />
like image 59
PeterKA Avatar answered Sep 03 '26 09:09

PeterKA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!