user1779796
user1779796

Reputation: 479

jQuery populate Select list based on text input's value


I am trying to write code that allows a select list to be populated based on the input value of a textbox.

For Example:
If user inputs milk in the textbox, the select list will contain "full fat", "Skimmed", "1% Milk"

I have been online and can't find any information on how to do this. I have managed to autopopulate one select list based on the selection from a previous one using jquery. However, I cant find a solution for when using a textbox.
Thanks for checking out my question!

Upvotes: 5

Views: 1970

Answers (1)

Gung Foo
Gung Foo

Reputation: 13558

create an object containing arrays of options:

selectOptions = {
   milk: ["full fat", "Skimmed", "1% Milk"]
}

based on this, you can append <option> tags to the <select> when the onchange event of the <textarea> fires:

$('textarea').change(function() {
   if(selectOptions[$(this).val()]) { // does the selectOptions object have an entry for the value of the textarea?
       $.each(selectOptions[$(this).val()], function() { // for each array item do
           $('select').append('<option>' + this + '</option>'); // append an option tag for the array item
       });
   }
});

Upvotes: 6

Related Questions