Reputation: 1065
I want to implement a functionality where user can search for different brands available with us. See the image to get what I'm looking for:
I want to search & replace a div with the brands matching my search. I'm looking for an idea here, I can easily do that with ajax call but I hope I can do this with simple javascript. Getting load time to as low as possible. Any ideas whether I can do this with simple javascript?
<input type='text' placeholder='Search' class='text'><br>
<input type='checkbox' id='a'>A<br>
<input type='checkbox' id='b'>B<br>
<input type='checkbox' id='c'>C<br>
<input type='checkbox' id='d'>D<br>
Simple html here (with no javascript code): http://jsfiddle.net/22nm8o34/
Upvotes: 0
Views: 1014
Reputation: 447
Here is my suggestion.
HTML:
<input type='text' placeholder='Search' class='text'><br>
<span class="checkbox-wrapper" id="a"><input type='checkbox' id='a'>A<br></span>
<span class="checkbox-wrapper" id="b"><input type='checkbox' id='b'>B<br></span>
<span class="checkbox-wrapper" id="c"><input type='checkbox' id='c'>C<br></span>
<span class="checkbox-wrapper" id="d"><input type='checkbox' id='d'>D<br></span>
Wrap each checkbox in a span so that you can hide both the checkbox and value.
Jquery:
$('.text').keyup(function submitClosure(ev) {
$('.checkbox-wrapper').each(function inputElementClosure(index, element) {
element = $(element);
if (element.attr('id').indexOf(ev.target.value) > -1) {
element.show();
} else {
element.hide();
}
});
});
Listen to the jQuery keyup event and loop throught each span. If the span id contains some of the input, show it, otherwise hide it.
Hope I understood you question correct? :)
Here is an link the to the updated jsfiddle http://jsfiddle.net/22nm8o34/8/
Link to lower case solution: http://jsfiddle.net/22nm8o34/10/
And a link to plain javascript solution: http://jsfiddle.net/22nm8o34/21/
Upvotes: 2