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!阅读原文】。感谢您的支持!


Bootstrap 4.1 发布,新增多项功能 Bootstrap 4.1 发布了。此次更新包括程序修复、文档更新、构建工具更改和一些小功能的新增。主要更新内容如下: 增加了新的自定义范围表单控...
Want to Bootstrap Your Startup? Every Founder Shou... Bootstrapping is in many ways the simplest way tostart a business. You don't ne...
6 Tips to Hone Your Bootstrap Skills in 2017 Bootstrap is not just an ordinary mobile responsive website creating progr...
Bootstrap Popover doesn’t work with MVC3 I'm trying to use "popover" with a "@Html.PasswordFor" MVC helper elemen...
Bootstrap Grid not aligned Thumbnails using twitter bootstrap are not aligned vertically ...