Swagg
Swagg

Reputation: 1196

how to create input (type = text) which accepts values from select option?

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?

Upvotes: 2

Views: 246

Answers (3)

David Jones
David Jones

Reputation: 10239

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));
    }
});

Upvotes: 2

Prasanna Aarthi
Prasanna Aarthi

Reputation: 3453

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" /> 

Upvotes: 0

sirhc
sirhc

Reputation: 6097

Chosen and Select2 are more suitable for this than typeahead:

Upvotes: 5

Related Questions