🤩Add elements dynamically full (ok)

Đọc thêm bài này để lấy giá trị

https://javascriptuse.gitbook.io/advanced/javascript-select-element-ok

Example 1

C:\xampp8\htdocs\lva\index.php

<!doctype html>
<html>
<head>
  <title>Add input fields to form dynamically using jQuery</title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <link rel="stylesheet" type="text/css" href="style.css" />
  <!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>-->
  <!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>-->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous
  "></script>
  <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js" integrity="sha256-lSjKY0/srUM9BE3dPm+c4fBo1dky2v27Gdjm2uoZaL0=" crossorigin="anonymous"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      var $fieldCount = 0;
      $('#addField').on('click', function() {
        $(".error").remove();
        $(".values").remove();
        if ($("#input_type").val() != "") {
          var $type = $("#input_type").val();
          $fieldCount++;;
          if ($type == 1) {
            var $node = '<p><label for="text' + $fieldCount + '">Text ' + $fieldCount + ': </label><input type="text" name="text' + $fieldCount + '" id="text' + $fieldCount + '"/><span class="removeField">Remove</span></p>';
          } else if ($type == 2) {
            var $node = '<p><label for="textarea' + $fieldCount + '">Textarea ' + $fieldCount + ': </label><textarea name="textarea' + $fieldCount + '" id="textarea' + $fieldCount + '"></textarea><span class="removeField">Remove</span></p>';
          } else if ($type == 3) {
            var $node = '<p><label for="file' + $fieldCount + '">File ' + $fieldCount + ': </label><input type="file" name="file' + $fieldCount + '" id="file' + $fieldCount + '"/><span class="removeField">Remove</span></p>';
          }
          $('p').last().after($node);
        } else {
          $error_msg = "<p style='color:red;' class='error'>Select input type<p>";
          $('form').prepend($error_msg);
        }
      });
      $('form').on('click', '.removeField', function() {
        $(this).parent().remove();
      });
    });
  </script>
</head>
<body>
  <div id="container">
    <h2>Add input fields to form dynamically using jQuery</h2>
    <form id="dynamic_inputs" method="post">
      <p>
        <select name="input_type" id="input_type">
          <option value="">-- Select Type --</option>
          <option value="1">Text</option>
          <option value="2">Textarea</option>
          <option value="3">File</option>
        </select>
        <span id="addField">Add Field</span>
      </p>
      <p>
        <label for="name">Name: </label>
        <input id="name" type="text" name="name">
      </p>
    </form>
  </div>
</body>
</html>

C:\xampp8\htdocs\lva\style.css

#container {
  width: 600px;
  margin: 20px auto;
  padding: 15px;
  background-color: #eee;
}
#addField {
  padding: 5px;
  display: inline-block;
  background-color: #3A9668;
  color: #f1f1f1;
  border: 1px solid #005;
}
.removeField {
  margin: auto;
  margin-left: 5px;
  padding: 5px;
  display: inline-block;
  background-color: #B02109;
  color: #f1f1f1;
  border: 1px solid #005;
}
#addField:hover,
.removeField:hover {
  cursor: pointer;
}
label {
  padding: 0 10px;
  display: block;
  float: left;
  width: 150px;
}
input,
textarea {
  padding: 5px;
  font-size: 14px;
}
input {
  width: 250px;
}
textarea {
  width: 290px;
  height: 150px;
}
select {
  padding: 5px;
}
.btn-submit {
  width: 100px;
  background-color: #428BCA;
  border-color: #357EBD;
}

Add dynamic form fields using AlpineJS link

<div class="row" x-data="handler()">
<div class="col">
<table class="table table-bordered align-items-center table-sm">
  <thead class="thead-light">
   <tr>
     <th>#</th>
     <th>Text Feild 1</th>                            <th>Text Feild 2</th>
     <th>Remove</th>
    </tr>
  </thead>
  <tbody>
    <template x-for="(field, index) in fields" :key="index">
     <tr>
      <td x-text="index + 1"></td>
      <td><input x-model="field.txt1" type="text" name="txt1[]" class="form-control"></td>
      <td><input x-model="field.txt2" type="text" name="txt2[]" class="form-control"></td>
       <td><button type="button" class="btn btn-danger btn-small" @click="removeField(index)">&times;</button></td>
    </tr>
   </template>
  </tbody>
  <tfoot>
     <tr>
       <td colspan="4" class="text-right"><button type="button" class="btn btn-info" @click="addNewField()">+ Add Row</button></td>
    </tr>
  </tfoot>
</table>
</div>
</div>
.row {
  max-width: 80%;
  margin: 20px auto;
}
function handler() {
    return {
      fields: [],
      addNewField() {
          this.fields.push({
              txt1: '',
              txt2: ''
           });
        },
        removeField(index) {
           this.fields.splice(index, 1);
         }
      }
 }

Example 2

How to add, remove, input fields with javascript

index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<!-- Setting the pages character encoding -->
	<meta charset="UTF-8">

	<!-- The meta viewport will scale my content to any device width -->
	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<!-- Link to my stylesheet -->
	<link rel="stylesheet" href="styles.css">
	<title>Adding dynamically input fields</title>
</head>
<body>
	<h2>Write a text note and press the plus button</h2>

	<div class="notes">
		<!-- content created by javascript -->
	</div>

	<form action="" method="post" autocomplete="off">

		<div class="field">
			<input type="text" name="notes[]">
			<span onclick="addField(this)">+</span>
			<span onclick="removeField(this)">-</span>
		</div>

		<button type="submit" >Display Notes</button>
		<button class="reset" onclick="location.reload()">Reset App</button>

	</form>

	<script src="script.js"></script> 
</body>
</html>

styles.css

*{
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}

body{
	font-family: sans-serif;
	min-height: 100%;
	color: #555;
	width:  600px;
	margin: 0 auto;
	padding-top: 20px;
}

h1{
	text-align: center;
	color:  #888;
}

.notes{
	padding: 20px;
}

.notes p{
	border-bottom: thin dotted #d4d4d4;
	padding: 20px 10px 0px 0px;
	font-style: italic;
	font-size: 18px;
}

.notes p span{
	font-size: 16px;
	float:  right;
	cursor: pointer;
	display: inline-block;
}
.notes p span.mark{
	color: green;
	font-size: 30px;
	transform: translateY(-10px);
}

form{
	width:  100%;
}

.field{
	margin-bottom: 10px;
	display: flex;
	transition: opacity 0.3s;
}

.field input{
	padding: 5px 10px;
	width: 100%;
	border: none;
	 border: thin solid #d4d4d4; 
	font-size: 20px;
	color: #888;
	font-family: ubuntu, sans-serif;
	background-color: #f9f9f9;
}
.field input:focus{
	outline: none;
}

.field span{
	display: inline-block;
	margin-left: 10px;
	cursor: pointer;
	background-color: #f9f9f9;
	padding: 10px;
	font-size: 20px;
	transition: all 0.3s;
	font-weight: bold;
	border: thin solid #d4d4d4; 
}
.field span:last-child{
	display: none;
	padding: 12px;
}
.field span:hover{
	background-color: green;
	border: thin solid green;
	color: #fff;
}
.field span:last-child:hover{
	background-color: red;
	border: thin solid red;
	color: #fff;
}


button{
	display: block;
	padding: 10px 20px;
	margin-top: 30px;
	width:  150px;
	float: left;
	font-size: 16px;
	background-color: #5b8ebf;
	border: thin solid #d5e4d4;
	cursor: pointer;
	color: #fff;
}

button:active{
	background-color: #aedea6;
	color: #000;
}

.reset{
	float: right;
	background-color: green;
}

script.js

function addField(plusElement){

	let displayButton = document.querySelector("form button");

	// Stopping the function if the input field has no value.
	if(plusElement.previousElementSibling.value.trim() === ""){
		return false;
	}

	// creating the div container.
	let div = document.createElement("div");
	div.setAttribute("class", "field");

	// Creating the input element.
	let field = document.createElement("input");
	field.setAttribute("type", "text");
	field.setAttribute("name", "notes[]");

	// Creating the plus span element.
	let plus = document.createElement("span");
	plus.setAttribute("onclick", "addField(this)");
	let plusText = document.createTextNode("+");
	plus.appendChild(plusText);

	// Creating the minus span element.
	let minus = document.createElement("span");
	minus.setAttribute("onclick", "removeField(this)");
	let minusText = document.createTextNode("-");
	minus.appendChild(minusText);

	// Adding the elements to the DOM.
	form.insertBefore(div, displayButton);
	div.appendChild(field);
	div.appendChild(plus);
	div.appendChild(minus);

	// Un hiding the minus sign.
	plusElement.nextElementSibling.style.display = "block"; // the minus sign
	// Hiding the plus sign.
	plusElement.style.display = "none"; // the plus sign
}

function removeField(minusElement){
   minusElement.parentElement.remove();
}

let form = document.forms[0];
form.addEventListener("submit", fetchTextNotes);
function fetchTextNotes(event){
	// prevent the form to communicate with the server.
	event.preventDefault();

	// Fetch the values from the input fields.
	let data = new FormData(form);

	// Storing the values inside an array so we can handle them.
	// we don't want empty values.
	let notes = [];
	data.forEach( function(value){
		if(value !== ""){
			notes.push(value);
		}
	});

	// Output the values on the screen.
	let out = "";
	for(let note of notes){
		out += `
			<p>${note} <span onclick="markAsDone(this)">Mark as done</span></p>
		`;
	}
	document.querySelector(".notes").innerHTML = out;

	// Delete all input elements except the last one.
	let inputFields = document.querySelectorAll(".field");
	inputFields.forEach(function(element, index){
		if(index == inputFields.length - 1){
			element.children[0].value = "";
		}else{
			element.remove();
		}
	});
}

function markAsDone(element){
	element.classList.add("mark");
	element.innerHTML = "&check;";
}

Example 3

Dynamically creating a specific number of input form elements

<html>
<head>
    <script type='text/javascript'>
        function addFields(){
            // Generate a dynamic number of inputs
            var number = document.getElementById("member").value;
            // Get the element where the inputs will be added to
            var container = document.getElementById("container");
            // Remove every children it had before
            while (container.hasChildNodes()) {
                container.removeChild(container.lastChild);
            }
            for (i=0;i<number;i++){
                // Append a node with a random text
                container.appendChild(document.createTextNode("Member " + (i+1)));
                // Create an <input> element, set its type and name attributes
                var input = document.createElement("input");
                input.type = "text";
                input.name = "member" + i;
                container.appendChild(input);
                // Append a line break 
                container.appendChild(document.createElement("br"));
            }
        }
    </script>
</head>
<body>
    <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
    <a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
    <div id="container"/>
</body>
</html>

Example 4

Add input elements dynamically [pure JS]

function add(type) {
  //Create an input type dynamically.
  var element = document.createElement("input");

  //Assign different attributes to the element.
  element.setAttribute("type", type);
  element.setAttribute("value", type);
  element.setAttribute("name", type);

  var foo = document.getElementById("fooBar");

  //Append the element in page (in span).
  foo.appendChild(element);
}
* {
  margin: 0;
  padding: 0;
  font-family: Arial;
}

body {
  background-color: grey;
}

h1 {
  color: white;
}

h2 {
  color: darkgrey;
}
<form>
  <h1>Add input elements dynamically</h1>
  <h2>Please select any type</h2>

  <div>
    <select name="element">
      <option value="file">File</option>
      <option value="text">TextBox</option>
    </select>

    <input type="button" value="add" onclick="add(document.forms[0].element.value)" />
    <span id="fooBar">&nbsp;</span>
  </div>
</form>

Example 5

How to Create a Form Dynamically with the JavaScript?

<!DOCTYPE html>
<html>
	<head>
		<title>
			Create a Form Dynamically with
			the JavaScript
		</title>
	</head>
	<body style="text-align: center;">
		<h1 style="color: green;">
			GeeksforGeeks
		</h1>
		<p>
		Click on the button to create
		a form dynamically
		</p>
		<button onClick="GFG_Fun()">
			click here
		</button>
		<p id="GFG_DOWN"></p>
<script>
	var down = document.getElementById("GFG_DOWN");
		
	// Create a break line element
	var br = document.createElement("br");
	function GFG_Fun() {
			
	// Create a form dynamically
	var form = document.createElement("form");
	form.setAttribute("method", "post");
	form.setAttribute("action", "submit.php");

	// Create an input element for Full Name
	var FN = document.createElement("input");
	FN.setAttribute("type", "text");
	FN.setAttribute("name", "FullName");
	FN.setAttribute("placeholder", "Full Name");

	// Create an input element for date of birth
	var DOB = document.createElement("input");
	DOB.setAttribute("type", "text");
	DOB.setAttribute("name", "dob");
	DOB.setAttribute("placeholder", "DOB");

	// Create an input element for emailID
	var EID = document.createElement("input");
	EID.setAttribute("type", "text");
	EID.setAttribute("name", "emailID");
	EID.setAttribute("placeholder", "E-Mail ID");

	// Create an input element for password
	var PWD = document.createElement("input");
	PWD.setAttribute("type", "password");
	PWD.setAttribute("name", "password");
	PWD.setAttribute("placeholder", "Password");

	// Create an input element for retype-password
	var RPWD = document.createElement("input");
	RPWD.setAttribute("type", "password");
	RPWD.setAttribute("name", "reTypePassword");
	RPWD.setAttribute("placeholder", "ReEnter Password");

				// create a submit button
				var s = document.createElement("input");
				s.setAttribute("type", "submit");
				s.setAttribute("value", "Submit");
				
				// Append the full name input to the form
				form.appendChild(FN);
				
				// Inserting a line break
				form.appendChild(br.cloneNode());
				
				// Append the DOB to the form
				form.appendChild(DOB);
				form.appendChild(br.cloneNode());
				
				// Append the emailID to the form
				form.appendChild(EID);
				form.appendChild(br.cloneNode());
				
				// Append the Password to the form
				form.appendChild(PWD);
				form.appendChild(br.cloneNode());
				
				// Append the ReEnterPassword to the form
				form.appendChild(RPWD);
				form.appendChild(br.cloneNode());
				
				// Append the submit button to the form
				form.appendChild(s);

				document.getElementsByTagName("body")[0]
			.appendChild(form);
			}
		</script>
	</body>
</html>

Example 6.1.1 Pure Vanila JS

Fujifilm/gbalb-demo.cybozu.com4913/live.html

<!DOCTYPE html>
<html lang="en">

<head>
  <!-- Setting the pages character encoding -->
  <meta charset="UTF-8">
  <!-- The meta viewport will scale my content to any device width -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
  <link rel="stylesheet" href="styles.css">
  <title>Adding dynamically input fields</title>
</head>
<script>
  var choices = ["one", "two","three"];
function addInput(divName) {
  var newDiv = document.createElement('div');
  var selectHTML = "";
  selectHTML = "<select>";
  for (i = 0; i < choices.length; i = i + 1) {
    selectHTML += "<option value='" + choices[i] + "'>" + choices[i] + "</option>";
  }
  selectHTML += "</select>";
  newDiv.innerHTML = selectHTML;
  document.getElementById(divName).appendChild(newDiv);
}
</script>

<body>
  <form class="new" method="post" action="/jobs">
    <div id="dynamicInput"></div>
    <input type="button" value="Add" onclick="addInput('dynamicInput');" />
    <input type="button" value="Save" />
  </form>
</body>

</html>

Example 6.1.2 Pure Vanila JS + sweetalert2

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <script src="http://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
  <link rel="stylesheet" href="styles.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.33/dist/sweetalert2.min.css">
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.33/dist/sweetalert2.all.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="script.js"></script>
  <title>Document</title>
  <style>
    select:empty {
      display: none !important;
    }
  </style>
</head>
<body>
  <script type="text/javascript">
  let timerInterval;
  var choices = ["one", "two", "three"];
  function addInput(divName) {
    var newDiv = document.createElement('div');
    var selectHTML = "";
    selectHTML = "<select class='getValue'>";
    for (i = 0; i < choices.length; i = i + 1) {
      selectHTML += "<option value='" + choices[i] + "'>" + choices[i] + "</option>";
    }
    selectHTML += "</select>";
    newDiv.innerHTML = selectHTML;
    document.getElementById(divName).appendChild(newDiv);
  }
  Swal.fire({
    title: 'Auto close alert!',
    html: `
      <div class="wrapper">
        <form class="new" method="post" action="/jobs">
          <div id="dynamicInput"></div>
          <input type="button" value="Add" onclick="addInput('dynamicInput');" />
          <input type="button" value="Save" />
        </form>
      </div>`,
    didOpen: () => {
      const content = Swal.getHtmlContainer();
      const $ = content.querySelector.bind(content);
      const select = $('.getValue');
      console.log(select);
    }
  }).then((result) => {
    console.log($(".getValue").find(':selected').val());
  });
  </script>
</body>
</html>

Example 6.2 jQuery Version

Fujifilm/gbalb-demo.cybozu.com4913/live.html

<!DOCTYPE html>
<html lang="en">

<head>
  <!-- Setting the pages character encoding -->
  <meta charset="UTF-8">
  <!-- The meta viewport will scale my content to any device width -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
  <link rel="stylesheet" href="styles.css">
  <title>Adding dynamically input fields</title>
</head>
<script>
  var choices = ["one", "two"];
  function addInput(divName) {
    var select = $("<select/>")
    $.each(choices, function(a, b) {
        select.append($("<option/>").attr("value", b).text(b));
    });
    $("#" + divName).append(select);
  }
</script>

<body>
  <form class="new" method="post" action="/jobs">
    <div id="dynamicInput"></div>
    <input type="button" value="Add" onclick="addInput('dynamicInput');" />
    <input type="button" value="Save" />
  </form>
</body>

</html>

Example 7

Fujifilm/gbalb-demo.cybozu.com4913/live.html

<!DOCTYPE html>
<html>

<head>
  <title>Dynamic DropDown List | Javacodepoint
  </title>
</head>

<body>
  <button onclick="dynamicDropdownList()">Create Dynamic Dropdown List
  </button>
  <br>
  <br>
  <div id="dropdown-container">
  </div>
  <script>
  //country data in string array format
  var countries = ["Australia", "France", "India", "Japan", "United States"];
  //This method calls on button click
  function dynamicDropdownList() {
    var dropdown = document.createElement("select");
    for (var i = 0; i < countries.length; i++) {
      var opt = document.createElement("option");
      opt.text = countries[i];
      opt.value = countries[i];
      dropdown.options.add(opt);
    }
    //Load the dynamically created dropdown in container
    var container = document.getElementById("dropdown-container");
    container.appendChild(dropdown);
  }
  </script>
</body>

</html>

Example 8

<!DOCTYPE html>
<html>

<head>
  <title>Dynamic DropDown List | Javacodepoint
  </title>
</head>

<body>
  <button onclick="dynamicDropdownList()">Create Dynamic Dropdown List
  </button>
  <br>
  <br>
  <div id="dropdown-container">
  </div>
  <script>
  //country data in json array format
  var countries = [{
    "code": "AU",
    "name": "Australia"
  }, {
    "code": "FR",
    "name": "France"
  }, {
    "code": "IN",
    "name": "India"
  }, {
    "code": "JP",
    "name": "Japan"
  }, {
    "code": "CH",
    "name": "Switzerland"
  }, {
    "code": "GB",
    "name": "United Kingdom"
  }, {
    "code": "US",
    "name": "United States"
  }];
  //This method calls on button click
  function dynamicDropdownList() {
    var dropdown = document.createElement("select");
    for (var i = 0; i < countries.length; i++) {
      var opt = document.createElement("option");
      opt.text = countries[i].name;
      opt.value = countries[i].code;
      dropdown.options.add(opt);
    }
    //Load the dynamically created dropdown in container
    var container = document.getElementById("dropdown-container");
    container.appendChild(dropdown);
  }
  </script>
</body>

</html>

Example 9

<!DOCTYPE html>
<html>

<head>
  <title>Dynamic DropDown List | Javacodepoint
  </title>
</head>

<body>
  <button onclick="dynamicDropdownList()">Create Dynamic Dropdown List
  </button>
  <br>
  <br>
  <div id="dropdown-container">
  </div>
  <script>
  //country data in json array format
  var countries = [{
    "code": "AU",
    "name": "Australia"
  }, {
    "code": "FR",
    "name": "France"
  }, {
    "code": "IN",
    "name": "India"
  }, {
    "code": "JP",
    "name": "Japan"
  }, {
    "code": "CH",
    "name": "Switzerland"
  }, {
    "code": "GB",
    "name": "United Kingdom"
  }, {
    "code": "US",
    "name": "United States"
  }];
  //This method calls on button click
  function dynamicDropdownList() {
    var dropdownHTML = '<select>';
    for (var i = 0; i < countries.length; i++) {
      var name = countries[i].name;
      var value = countries[i].code;
      dropdownHTML += '<option value="' + value + '">' + name + '</option>';
    }
    dropdownHTML += '</select>';
    //Load the dynamically created dropdown in container
    var container = document.getElementById("dropdown-container");
    container.innerHTML = dropdownHTML;
  }
  </script>
</body>

</html>

Example 10

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Setting the pages character encoding -->
  <meta charset="UTF-8">
  <!-- The meta viewport will scale my content to any device width -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
  <link rel="stylesheet" href="styles.css">
  <title>Adding dynamically input fields</title>
  <style>
  label {
    font-size: 1rem;
    font-family: sans-serif;
    padding-right: 10px;
  }
  button,
  select {
    font-size: .9rem;
    padding: 2px 5px;
  }
  </style>
</head>
<body>
  <html>
  <body>
    <div id="container"></div>
    <br>
    <div>
      <button id="generate">Generate</button>
    </div>
  </body>
  <script>
  $(document).ready(function() {
    $('#generate').click(function() {
      var values = ["dog", "cat", "parrot", "rabbit"];
      var select = $('<select>').prop('id', 'pets')
        .prop('name', 'pets');
      $(values).each(function() {
        select.append($("<option>")
          .prop('value', this)
          .text(this.charAt(0).toUpperCase() + this.slice(1)));
      });
      var label = $("<label>").prop('for', 'pets')
        .text("Choose your pets: ");
      var br = $("<br>");
      $('#container').append(label).append(select).append(br);
    })
  });
  </script>
  </html>

Example 11

<!DOCTYPE html>
<html lang="en">

<head>
  <!-- Setting the pages character encoding -->
  <meta charset="UTF-8">
  <!-- The meta viewport will scale my content to any device width -->
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
  <link rel="stylesheet" href="styles.css">
  <title>Adding dynamically input fields</title>
  <style>
  label {
    font-size: 1rem;
    font-family: sans-serif;
    padding-right: 10px;
  }

  button,
  select {
    font-size: .9rem;
    padding: 2px 5px;
  }
  </style>
</head>

<body>
  <html>

  <body>
    <select id="dynamic-select">
      <option value="1">one</option>
      <option value="2">two</option>
      <option value="3">three</option>
    </select>
    <button onclick="addOption()">add item</button>
    <button onclick="removeOption()">remove item</button>
    <button onclick="removeAllOptions()">remove all</button>
  </body>
  <script>
  function addOption() {
    var select = document.getElementById("dynamic-select");
    select.options[select.options.length] = new Option('New Element', '0');
  }

  function removeOption() {
    var select = document.getElementById("dynamic-select");
    select.options[select.options.length - 1] = null;
  }

  function removeAllOptions() {
    var select = document.getElementById("dynamic-select");
    select.options.length = 0;
  }
  </script>

  </html>

Last updated