Bootstrap Select Menu – Add New Option

综合技术 2018-05-18 阅读原文

I have a simple Bootstrap form with a select input:

Fruit Vegetables

The users now have a requirement to be able to add a new option dynamically to the select menu rather than be restricted to the items on the select menu.

I'm not sure if it's possible to modify a select menu and how to make it consistent with the rest of the Bootstrap framework?

To add an option dynamically, there should be a UI button giving you that choice. To get user input, we can use the window.prompt

We then create an option element, set its value attribute and set its name. Then just append these elements and nodes to the DOM with appendChild

Try playing around with this. I added some items like Steak, potatoes and beer.

var addOption = document.getElementById("add-option");
var selectField = document.getElementById("category");
addOption.addEventListener("click", function() {
    var item = prompt("What would you like");
    var option = document.createElement("option");
    option.setAttribute("value", item);
    var optionName = document.createTextNode(item);

Fruit Vegetables

Hello, buddy!

责编内容by:Hello, buddy!阅读原文】。感谢您的支持!