Adding a fresh selection to the Bootstrap menu

I'm working on a straightforward Bootstrap form that includes 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>

Now, there is a new requirement from users to be able to dynamically add a new option to the select menu instead of being limited to the pre-defined items.

I am unsure if it's possible to modify a select menu in this way while maintaining consistency with the rest of the Bootstrap framework?

Answer №1

If you want to dynamically add an option, make sure there is a user interface button available for that purpose. User input can be obtained by utilizing the window.prompt method.

Create an option element, assign a value to its attribute, and set its name accordingly. Subsequently, append these elements and nodes to the Document Object Model using the appendChild method.

Feel free to experiment with this functionality. I have included some sample items such as Steak, potatoes, and beer.

var newOptionBtn = document.getElementById("add-option");
var categorySelect = document.getElementById("category");
newOptionBtn.addEventListener("click", function() {
    var itemToAdd = prompt("Enter your item:");
    var createdOption = document.createElement("option");
    createdOption.setAttribute("value", itemToAdd);
    var optionText = document.createTextNode(itemToAdd);
    createdOption.appendChild(optionText);
    categorySelect.appendChild(createdOption);
});
<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 New Option</button>

Answer №2

Is this what you are looking for?

Here is an example of a select dropdown menu:

<select id="city" class="dropdown">
        <option>City A</option>
        <option>City B</option>
        <option>City C</option>
</select>

Using jQuery:

$('.dropdown').selectpicker();
$("#city").on('change', function () {
   $(this)
       .append('<option>City D</option><option>City E</option>')
       .selectpicker('refresh');
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on playing two HTML5 videos simultaneously once they have been loaded

Is it possible to make two HTML5 videos autoplay simultaneously? Is there a way to delay the playback until both videos have fully loaded? I'm looking to ensure that neither video starts playing before the other has finished loading. Does that clarif ...

What is the reason behind the unsuccessful deep copy of jQuery for localStorage?

When using localStorage in JavaScript, the value retrieved may display as [object Object] instead of the expected result. This issue seems to be specific to certain variables. Check out this sample code: var some_hash = { "key1":"value1", "key2": "value2 ...

Steps for closing a Bootstrap 4 Pop-up using the X button alongside a carousel

I need help with closing a Bootstrap 4 pop-up only when the X icon is clicked. If I remove the 'data-backdrop="static"' code, the pop-up closes whenever I click outside the modal, but this is not ideal as it would also close when trying to intera ...

Attempting to send a Promise to another function for it to return, encountering an error of "Unhandled promise rejection"

My goal is to develop a versatile database update function that can be utilized for creating more customized update functions. Within the module database.js, the following code is present: const {Pool,Client}=require('pg'); const pool=new Pool( ...

Incorporating external JavaScript files into a React Element

I am currently revamping my Portfolio Site to incorporate modals into one of the pages as part of the transition to a Single Page Application (SPA). The JavaScript code for these modals is stored in a "main.js" file, and the necessary tags are included in ...

The image filter plugin is functioning properly in one project, however, it is not working in

After successfully using a plugin from w3schools to filter elements in one project, I encountered an issue when attempting to implement it in another project. Here is the link to the problematic code pen: https://codepen.io/zakero/pen/mZYBPz If anyone ca ...

Utilizing Ajax in ASP.NET to Execute a Controller's Void Method when Clicking a Button

I have a project for a .ASP MVC Web Application. My goal is to trigger a void method in the controller class when I click a button using AJAX. There is no need for any input or output data, just simply creating a PDF file and saving it locally. Currently, ...

How can I access a child element within an element using Protractor?

I'm struggling to access the child element of an ng-repeat element. After searching for solutions, I came across suggestions that didn't work for me. One tip was to try something like this: var parent = element(by.repeater('')); var c ...

Inspect the json data to find a specific value and then determine the corresponding key associated with

I am currently working with JSON data retrieved from which I am storing in a variable. Despite my limited experience with JSON/JS, I have been unable to find a solution through online searches. Here is the code snippet: function checkMojang() { var moj ...

Do I require a Javascript framework, or can I achieve the desired functionality with the

During my time building Microsoft Excel apps using VBA, I worked with events like _Change and _Click. Transitioning to JavaScript and frameworks was a bit overwhelming due to the asynchronous nature of it all. Moving on to Python and Flask has been a ref ...

difficulty with ajax to exhibit the information from a basic document

I'm trying to achieve a simple task using ajax. On my Mac, I have a folder containing 2 documents: index.html and text.txt. index.html : <p> <input type="button" onclick="loadDoc()" value="CLICK" /> </p> <p id="fileContent"&g ...

Loop through an array of objects that each contain two sub-objects using ng

I'm looking to organize each data-record in an object that contains two other objects structured like this: data Object { abbData={...}, invoiceData={...}} abbData Object { service="24", conn_fee="0", month_fee="249", more...} invoiceData ...

"Which is better to use with jQuery: the .on method for handling

//creating toolbar elements dynamically var $toolbar = $(".toolbar"); $.each(tools, function (i, tool) { $("<img>", tool).appendTo($toolbar); }); var $tools = $toolbar.find("img"); //defining drag and drop functionality $toolbar.on("dragstart", ...

Resizing and uploading multiple images with accompanying descriptions

I am in need of a solution for uploading multiple images along with descriptions. Users will be uploading 1-10 large-sized images from cameras, so it would be ideal if the images could be resized before the upload. My requirements are: Compatibility wit ...

Having issues with showing an image from a specified component in a separate file

I am facing an issue where my image is not displaying in the app.js file, even though I have imported it from another file named comp.js. Here is the current code in app.js: import React from 'react'; import TextImg from "./Comp"; impor ...

Accessing fields from other sources in ng-repeat can be accomplished by utilizing special syntax within the ng-repeat directive

I have a unique challenge where I need to utilize the firstkey from one AngularJS model, firstcollection, as an index value in another collection called anothercollention. Essentially, I want to iterate over the values in anothercollention based on the k ...

Ember: Utilizing Models as Data Sources for CollectionViews

I am looking to integrate model data retrieved from an ajax request into the content of an Ember.CollectionView in order to create a list of items. My goal is to display a list showing the title from each object in the array received from the API. I am cur ...

Ways to disable an element

How can I prevent a <form:input type="text" path="lateTimeValue" disabled="true" id="lateTime" /> element from sending its value to the server when disabled? What steps should I take to ensure the value is not passed to the server upon submissio ...

Could someone provide me with a breakdown of this code utilizing the .bind() function?

The code snippet above is from the jQuery source code and it deals with event handling. It defines an array of events, such as click, focus, blur, etc., and then adds each event to the jQuery prototype using a forEach loop. var events = ['click', ...

When utilizing row.add in AngularJS and jQuery DataTables, the ng-click function may not function as expected

As a newcomer to angularjs, I have successfully implemented the jQuery DataTable directive with angularJS. However, I am encountering an issue when trying to add a JavaScript function to "TR" dynamically using "ng-click", as it does not seem to be recogniz ...