user2131422
user2131422

Reputation: 33

How to dynamically populate a select box based on text box input

I have a text box and a select box as box. The select box values are loaded via ajax call based on the selection in another select box. Now my requirement is as I input value in the text box based on the input my select box should show the values.

<form:input id="txtBox"></form:input>

<form:select id="selectBox" path="selectedValue">
  <form:option value="0">Anand</form:option >
  <form:option value="1">Arun</form:option >
  <form:option value="2">Ananya</form:option >
  <form:option value="3">babu</form:option >
</form:select>

Now I enter 'a' in the text box the select box should be populated with "Anand","Arun","Ananya".

if I enter 'n' again in the txt box "Anand" and "Ananaya" should be listed.

If I enter any alphabet in the text box that is not in the select box then the select box should be empty.

How to achieve this in Jquery?

Upvotes: 0

Views: 1556

Answers (1)

Sam
Sam

Reputation: 926

Firstly, as others have mentioned you should have a look at http://jqueryui.com/autocomplete which provides a excelent option for doing exactly what you described.

If you would prefer not to use a plugin then you can do something like this: jsFiddle Demo

$(function() {

    $('input[type=text]').keyup(function() {

        $('select option:contains("' + $('input[type=text]').val() + '")').show().siblings().hide();

    });

});

n.b. this is only a crude proof of concept, it would need refining before you use it in a production situation.

Upvotes: 2

Related Questions