2

In html we create input box as input(type='text') and

<select>
 <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>
 <option value="opel">Opel</option>
 <option value="audi">Audi</option>
</select>

How do you make a text box, which permits option only from options provided for, either thru (the select tag or otherwise). The idea is that the user can type the input rather than to have to choose from dropdown.

I can use typeahead. But how to confine inputs limited to typeahead options. Thru javascript? Is that the only solution?

1
  • In short you want Auto Complete Right :) Commented Aug 27, 2013 at 6:52

3 Answers 3

5

Chosen and Select2 are more suitable for this than typeahead:

Sign up to request clarification or add additional context in comments.

2 Comments

Amazing! Thanks! :) I was actually looking for the select multiple to tag option as well! Cheers
No problem. I have run into this exact problem before, so I know your pain. :)
2

Some great plugins were mentioned, but if you're looking for a more customizable solution, you could easily accomplish this with a few lines of jQuery. The following code will restrict the input to a pre-defined list of words (in this case, the list is defined in the HTML markup, but the list could also be implemented in the JavaScript). You could easily extend this solution to do exactly what you want. Here's a fiddle.

HTML

<input type="text" data-values="Volvo,Saab,Opel,Audi">

JavaScript

$("input").on("keyup", function() {
    var input = $(this).val();
    var values = $(this).data("values").split(",");
    var found = false;
    $(values).each(function(index, value) {
        if (value.toLowerCase().indexOf(input.toLowerCase()) > -1) {
            found = true;
        }
    });
    if (!found) {
        $(this).val($(this).val().slice(0,-1));
    }
});

1 Comment

No problem! Good luck on your project.
0

you can do this with autocomplete,

   var givenoptions = ["Volvo", "Saab", "Opel", "Audi"]
   empty = "";

    $('#selecttext').autocomplete({
autoFocus: true,
source: givenoptions
 }).keyup(function() {
   var isValid = false;
   for (i in givenoptions) {
    if (givenoptions[i].toLowerCase().match(this.value.toLowerCase())) {
        isValid = true;
    }
}
if (!isValid) {
    this.value = empty
} else {
    empty = this.value;
}
});


 <input id="selecttext" /> 

Comments

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.