Bootstrap Select Menu – Add New Option

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!责编内容来自:Hello, buddy! (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Bootstrap Select Menu – Add New Option

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录