Reputation: 63
<input type="text" id="filter">
<select id="asd">
<option>asd</option>
<option>zxc</option>
<option>qwe</option>
<option>cvb</option>
</select>
I wanted to do something like this, when i write in text input (for example "zxc") then <option>zxc</option>
will be selected.
Upvotes: 1
Views: 343
Reputation: 82267
You are going to want to use a large combination of features to do this. jQuery provides the feature .on
("input"
which will take a variety of event handlers on an input element and produce the "live" aspect you are looking for. Next you are going to have to take the entered text, and filter through the options to see if any of them match that. jQuery's filter
provides for this, binding the current element to the callback function during iteration. All that is left is to take the select element and assign the selectedIndex
to the index()
of the bound element when there is a match.
It looks like this:
var sel = $("#asd option"),
$f = $("#filter").on("input",function(){
var opt = sel.filter(function(){ return $(this).text() == $f.val(); });
if(opt.length) sel[0].parentNode.selectedIndex = opt.index();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="filter">
<select id="asd">
<option>asd</option>
<option>zxc</option>
<option>qwe</option>
<option>cvb</option>
</select>
Upvotes: 1
Reputation: 21
Start by putting an on state change for the text field.. each time the field changes, look at the string that's in the text field.
Now every time you look at the string, check to see if the text field contains "asd", now check if it contains "zxc" and so on, you could actually just check to see if the text field input starts with a...and so on...if it does, then you can manually set the option to be selected.
Upvotes: 0