简体   繁体   中英

Bootstrap Select Menu - Add New Option

I have a simple Bootstrap form with a select input:

 <div class="form-group"> <label for="category" class="control-label col-sm-3">Category</label> <div class="input-group col-xs-8"> <select class="form-control" name="category" id="category"> <option value="Fruit">Fruit</option> <option value="Vegetables">Vegetables</option> </select> </div> </div> 

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 method.

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); option.appendChild(optionName); selectField.appendChild(option); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> <div class="form-group"> <label for="category" class="control-label col-sm-3">Category</label> <div class="input-group col-xs-8"> <select class="form-control" name="category" id="category"> <option value="Fruit">Fruit</option> <option value="Vegetables">Vegetables</option> </select> </div> </div> <button id="add-option" class="btn btn-primary">Add a new option</button> 

You mean something like this?

some select

<select id="region" class="selectpicker">
        <option>region 1</option>
        <option>region 2</option>
        <option>region 3</option>
</select>

jquery js

$('.selectpicker').selectpicker();
$("#region").on('change', function () {
   $(this)
       .append('<option>region4</option><option>region5</option>')
       .selectpicker('refresh');
});

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