5


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!

1 Answer 1

6

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
       });
   }
});
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for helping. I have tried, but it doesnt seem to work. Think i'm going wrong somewhere. If I entered milk in the text box would the select list be populated with "full fat", "skimmed", "1% Milk"?
the onchange event fires if you deselect the textbox.. you can also use onkeyup, which fires on each keypress.
sorry.. i hadn't tested the code i wrote ;) i updated it and it works now.. look here for a testcase: jsfiddle.net/xeVBm/4
Ok I tried but still can't get it to work. Thanks so much for your time but could you see what I have done and tell me where I'm going wrong? jsfiddle.net/echoes13/C83DB
the object you defined has a syntax error. use the javascript console!! (i recommend firebug if you use firefox)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.