Using JavaScript, learn how to dynamically add a `<select class="form-control">` in Bootstrap

Currently delving into the realms of Bootstrap and jQuery, these are both new territories for me.

I am looking to use JavaScript to dynamically create the

<select class="form-control">
tag.

In my JavaScript code snippet, I have this:

var response = originalRequest.responseXML;
var property = document.createElement("select");
property.id = "predicate(" + addprop.level + "," + addprop.count + ")";
property[property.length] = new Option("Properties", "");
var options = response.getElementsByTagName('option');

My understanding is that document.createElement("select") allows for the dynamic creation of the select tag.

My query is how can I style this dynamically generated select tag using Bootstrap (specifically with class="form-control")?

The goal is to have the dropdown dynamically generated through jQuery/JavaScript without relying on the select tag in the HTML/JSP file.

Answer №1

One way to achieve this is by using the following code snippet:

property.className = "form-control";

Here's the complete solution:

var response = originalRequest.responseXML;
var property = document.createElement("select");
property.className = "form-control";
property.id = "predicate(" + addprop.level + "," + addprop.count + ")";
property[property.length] = new Option("Properties", "");
var options = response.getElementsByTagName('option');

For more detailed information, you can refer to MDN here.

Answer №2

If you utilize the $('element') method, you can easily create any document element and then utilize the .append(element) function to place that element within the desired parent. Feel free to test out my code to see if it functions correctly

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
  <form role="form">
    <div class="form-group" id="div">

<!-- begin snippet: js hide: false -->
      <label>Select</label>
    </div>
  </form>
<script>
  $(document).ready(function(){
    var select = $('<select class="form-control"></select>');
    var option = $('<option value="foo">Foo</option');
    select.append(option);
    $("#div").append(select);
  }); 
</script>
</body>
</html>

Answer №3

My passion lies in innovating and developing original creations, such as the project showcased here: https://jsfiddle.net/Ljdxnwot/5/. I enjoy crafting engaging written content alongside these endeavors.

let text = "<input type='text' class='form-input'>";

Answer №4

Utilize the $('element') function to generate any document element and then employ the .append(element) method to place the element within the desired parent container. Feel free to test out my code below:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
  <form role="form">
    <div class="form-group" id="div">
      <label>Select</label>
    </div>
  </form>
<script>
  $(document).ready(function(){
    var select = $('<select class="form-control"></select>');
    var option = $('<option value="foo">Foo</option>');
    select.append(option);
    $("#div").append(select);
  }); 
</script>
</body>
</html>

      <label>Select</label>
    </div>
  </form>
<script>
  $(document).ready(function(){
    var select = $('<select class="form-control"></select>');
    var option = $('<option value="foo">Foo</option>');
    select.append(option);
    $("#div").append(select);
  }); 
</script>
</body>
</html>

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

What is the best way to retrieve an object value within an if statement?

What can I do to ensure that the line within the if statement functions properly? const player1 = { name: "Ashley", color: "purple", isTurn: true, play: function() { if (this.isTrue) { return `this["name"] is current ...

angular ui-grid event: column clicked

I want to retrieve the selected column value based on the selection of a column in a UI grid. Once I have this value, I need to filter another UI grid table using it. How can I trigger a function when a column is selected and access the selected column val ...

Display a label upon hovering over an image

Is there a way to create an effect where upon hovering over an image, a pop-up image is displayed like this: https://i.sstatic.net/OloUH.png Any suggestions on how I can achieve this using HTML and CSS? Thanks in advance! ...

Cross-Origin Resource Sharing using Express.js and Angular2

Currently, I am attempting to download a PLY file from my Express.js server to my Angular/Ionic application which is currently hosted on Amazon AWS. Here is the Typescript code snippet from my Ionic app: //this.currentPlyFile contains the entire URL docum ...

The absence of HttpOnly Secure Cookies being transmitted

Here we go again, another inquiry regarding httpOnly Cookies. Seems like many others are facing the same predicament as me. Even though I receive the cookie from the server, it doesn't accompany other requests. I have mysite.example.com in angularj ...

Customize the background color of InfoBox in Google Maps API V3 using a dropdown menu

I'm attempting to dynamically change the background color of an InfoBox by using a Dropdown list (this InfoBox is used to create map labels). I am using google.maps.event.addDomListener, but the values are not returning. Below is my code, can anyone i ...

Guide to customizing the default scrollbar colors in Nextjs

When browsing websites like tailwindcss.com or https://developer.mozilla.org/ in Chrome and Firefox, you may have noticed that they utilize the default scrollbar style but allow users to change its colors through a dark/light mode button. The appearance of ...

Sequelize does not automatically include a junction table in the associated model data

Imagine having two models, User and Event, established in a many-to-many relationship with User.belongsToMany(Event) and Event.belongsToMany(User). Everything seems to be functioning properly until executing User.findAndCountAll({include: [{model: Event}]} ...

utilizing the JavaScript SDK to send alerts to a user's friends on Facebook

I am attempting to send a notification to a user's friend using the JS SDK on a Facebook canvas app, but I'm encountering this error in the console: POST https://graph.facebook.com/16542203957691/notifications? 400 (OK) jquery.min.js:140 c.exten ...

CSS positioning problems thoroughly elucidated

I'm facing two issues that I can't seem to resolve. My goal is to recreate a design similar to the one found at https://i.sstatic.net/XfPqm.jpg. My first issue is with adjusting the box in the header to stay aligned next to my headline tags. The ...

Selecting multiple objects in FabricJS on mouse click

Can anyone provide suggestions on how to select multiple objects on a canvas with a mouse click? I only want to select objects that overlay the point. From my understanding, the target of the mouse event is always the top-most object. I have tried binding ...

Add the content script to a webpage just one time

I am looking to inject a content script on context menu click in an extension manifest version 3. I need a way to determine if the script is already injected or not. If it hasn't been injected yet, I want to inject the content script. This condition m ...

A guide on retrieving the upload status of a file using an AJAX post request

Is there a way to retrieve the status of uploaded files when the user cancels the process while uploading multiple files using an ajax call? This is how I am currently making the ajax request to upload files: var request = $.ajax({ url: 'file ...

Why does the second JavaScript form validation not function correctly when compared to the first?

Here is a form that I have created: <form action="next.html" id="userInput" method="post" onsubmit="return validate();"> Age: <input type="text" name="age" id="age"/> function validate() { var age = document. ...

Ways to conceal and reveal image and text elements based on array loop output

I am currently working on setting up a questionnaire. The questions and answer options are being pulled from a database using an API. Some of the options include images, with the image link stored in the database. I am trying to find a solution where text ...

Ways to modify the color of every appearance of a term in an html grid using css

My HTML code includes an AngularJS table as shown below: <table id="searchTable"> <thead> <tr> <th>Index</th> <th>Observation</th> <th>Reported By</th> ...

I need help figuring out how to get a horizontal scrollbar positioned at the top of a div to function properly once the content has been loaded using ajax

HTML CODE <div id="scrollidout" style="overflow: auto; overflow-y: hidden; "> <div id="scrollidin" style="padding-top: 1px; height: 20px; width: 1000px">&nbsp;</div> </div> <div class="resultcontent" style="overflow ...

There seems to be a mysterious absence of chuck norris jokes in

I'm attempting to call two different APIs by clicking a button to display a random joke on the screen. I've created two separate functions to fetch the APIs and used Math.random() to generate a random number. If the number is greater than 50, one ...

Tips for comparing array objects in two separate React states

Comparing object arrays in two different React states can be challenging. Here is an example of the state values: review1 = [{name: John, Title: Manager},{name: Peter, Title: Engineer}, {name: Serena, Title: Supervisor}] review2 = [{personName: John, isma ...

Having difficulty erasing the existing input

I'm trying to create a form input field in JavaScript that generates a specified number of additional inputs based on user input. The issue I'm facing is that while the code works and adds more input fields, it does not delete the previously gene ...