Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editable Combo Box Javascript and HTML

I need to do the following thing: Using JavaScript, the HTML input tag having the text type and a select tag (combo box), create an editable combo box.

I have no idea how to make a combo box editable. Can you give me some suggestions, please?

I create the combo box like this, but is obviously not editable:

<html>
    <label>Your preferred programming language: </label>
    <select id="combobox">
        <option value="">Select one...</option>
        <option value="ActionScript">ActionScript</option>
        <option value="AppleScript">AppleScript</option>
    </select>
</html>

Where should I use the input tag?

like image 701
DianaM Avatar asked Dec 24 '22 06:12

DianaM


2 Answers

HTML5 includes the datalist element which solves this problem! :)

<html>
    <label>Your preferred programming language: </label>
    <input type="text" list="combo-options" id="combobox">
    <datalist id="combo-options">
        <option value="ActionScript">ActionScript</option>
        <option value="AppleScript">AppleScript</option>
    </datalist>
</html>
like image 195
deiga Avatar answered Jan 16 '23 13:01

deiga


Try something like this:

<label>Your preferred programming language: </label>
<input type="text" id="new_value"/>
<select id="combobox">
    <option value="">Select one...</option>
    <option value="ActionScript">ActionScript</option>
    <option value="AppleScript">AppleScript</option>
</select>



$("#new_value").keyup(function (e) {
    if (e.keyCode == 13) { // enter key
        var value = $(e.currentTarget).val();   // store the value from the input tag
        var option = $("<option/>");            // create a new option tag
        option.val(value).text(value);          // set the value attribute as well as the content
        $("#combobox").append(option);          // insert the new object to the dom
    }
});
like image 20
Alex Avatar answered Jan 16 '23 13:01

Alex