简体   繁体   中英

How to create a dropdown list with predefined values but there should also be the option to add a new one to the list

I want to create a dropdown list with predefined values but there should also be an option to add a new one to the list.

    <select name="" id="input" class="form-control" required="required">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="">Enter new value</option>
    </select>

In the above code I want an option to add new <option> tag, with which I could add a new value to the list and post to the server.

Here you can find the solution with jQuery:

https://jsfiddle.net/pqkczuah/

or alternatively you can use the following:

  $("#input").change(function() { if(this.value == "add") { varNewValue = prompt("Enter new value!"); $("#input").append("<option value='"+varNewValue+"'>"+varNewValue+"</option>"); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <select name="" id="input" class="form-control" required="required"> <option value="-">--- Select ---</option> <option value="add">Add New</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> 

Have the page respond, so chose the option vale

<option value="">New value</option>

have a script which onclick(); will make an text input box appear. When submitted send to a database and then make it a live dropdown.

Thats what I would do, long method but will get the job done and prevent further issues in the future.

you could provide the user with a input of type text to set value/text for the option .

 var select = document.querySelector('#input'); var btn = document.querySelector('button'); btn.onclick = function() { var inp = document.querySelector('#newitem'); //get input's value and create a option from it var val = inp.value; var option = new Option(val, val); select.add(option); }; 
 <select name="" id="input" class="form-control" required="required"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <input type="text" id="newitem"> <button>add option</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM