How to Dynamically Create <option> elements within a parent <optgroup> - javascript

I am trying to dynamically generate a structure similar to
<select>
<optgroup>
<options> option 1 </option>
<options> option 2 </option>
etc..
</optgroup>
</select>
using the following code. As you can see from the debug screen I can't seem to get the options embedded within the <optgroup>. Can anyone help please?
milestoneData =[{"phase_ID":21,"phase_name":"hello1"}, {"phase_ID":22,"phase_name":"hello2"}]
var optionGroup = document.createElement("optgroup");
optionGroup.setAttribute("label","Project 1");
optionGroup.setAttribute("value","100");
$(".test").append(optionGroup).attr("id","theid");
for (var i = 0; i < milestoneData.length; i++) {
var option = document.createElement("option");
option.setAttribute("value",milestoneData[i].phase_ID);
option.innerHTML=milestoneData[i].phase_name;
$('#theid').append(option);
}
HTML anchor is <select id = "testid" name = "testing" class ="test" >

You are almost there, the problem you currently have its at $(".test").append(optionGroup).attr("id","theid");
You currently are saying append optionGroup to .test and add id to .test element, which in your case you should add the id to optionGroup
So it would be something like this:
$(document).ready(function() {
milestoneData =[{"phase_ID":21,"phase_name":"hello1"}, {"phase_ID":22,"phase_name":"hello2"}]
var optionGroup = document.createElement("optgroup");
optionGroup.setAttribute("label","Project 1");
optionGroup.setAttribute("value","100");
optionGroup.setAttribute("id","theid");
$(".test").append(optionGroup);
for (var i = 0; i < milestoneData.length; i++) {
var option = document.createElement("option");
option.setAttribute("value",milestoneData[i].phase_ID);
option.innerHTML=milestoneData[i].phase_name;
$('#theid').append(option);
}
});
I've created a quick jsfiddle for you: https://jsfiddle.net/gcpn10kd/1/
You can check here some examples how optgroup should be structured

Set id to optgroup like <optgroup id="optgroupID">
In JS: (assume that we are adding 3 more options)
var id = document.getElementById("optgroupID");
var value = document.getElementById("optgroupID").innerHTML;
for(var i=0;i<3;i++){
value += "<option>"+i+"</option>";
}
id.innerHTML = value;

#Alexander, you need to append option with optgroup, then optgroup group will be append to select. See the solution
$(document).ready(function(){
var milestoneData =[{"phase_ID":21,"phase_name":"hello1"}, {"phase_ID":22,"phase_name":"hello2"}]
var optionGroup = document.createElement("optgroup");
optionGroup.setAttribute("label","Project 1");
optionGroup.setAttribute("value","100");
$(".test").append(optionGroup).attr("id","theid");
for (var i = 0; i < milestoneData.length; i++) {
var option = document.createElement("option");
option.setAttribute("value",milestoneData[i].phase_ID);
option.innerHTML=milestoneData[i].phase_name;
optionGroup.append(option);
}
$('#theid').append(optionGroup);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id = "testid" name = "testing" class ="test" ></select>

You're mixing up jQuery with vanilla javascript. I'd recommend using jQuery entirely if you're going to use that in your site.
You could benefit from a smaller code:
$(document).ready(function() {
var milestoneData = [{ "phase_ID": 21, "phase_name": "hello1" }, { "phase_ID": 22, "phase_name": "hello2" }];
var optionGroup = $("<optgroup/>", {
label: 'Project 1',
value: '100'
});
for (var i = 0; i < milestoneData.length; i++) {
var option = $("<option/>", {
value: milestoneData[i].phase_ID,
text: milestoneData[i].phase_name
});
optionGroup.append(option);
}
$(".test").append(optionGroup);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="test">
</select>

Related

How to generate multiple <select> elements with option tags?

I'm trying to append the defined select element to the document.
This answer, describes quite well about fixed arrays, but in my case I have a slice which is applied to the template by ExecuteTemplate method, so the value of <option> tags are defined by slice values.
Here is my code which does not work, as it should:
<html>
<input type="number" id="count">
<select id="select">
{{ range .Slice }}
<option value="{{ .Name }}">{{ .Name }}</option>
{{ end }}
</select>
<div class="test"></div>
<button onclick="generateSelects();">Test</button>
</html>
<script>
function generateSelects() {
var count = document.getElementById("count").value;
var i;
var select = document.getElementById("select");
var divClass = document.getElementsByClassName("test");
for (i = 0; i < Number(count); i++) {
divclass[0].appendChild(select);
)
}
</script>
What am I looking for is about generating select list based on the user's input. For example if the user enters 2, so two select menu going to appear on the screen.
How can I do this?
First of all make sure that generated selects all have different IDs, in your example they all have the same id which is "select".
Then instead of appending the "original" select element, try to clone it then add its clone to your div.
What I would do is :
function generateSelects() {
var count = document.getElementById("count").value;
var i;
var select = document.getElementById("select");
var divClass = document.getElementsByClassName("test");
for (i = 0; i < Number(count); i++) {
var clone = select.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = "some_id";
divclass[0].appendChild(clone);
}
}
Hope it helps!
To append multiple select elements, first you have create a select element. You can not directly get an elementById and append different element as child.
<script>
function generateSelects() {
var count = document.getElementById("count").value;
var i;
var divClass = document.getElementsByClassName("test");
for (i = 0; i < Number(count); i++) {
var option = document.createElement("OPTION");
option.setAttribute("value", "optionvalue");
var select = document.createElement("SELECT");
select.appendChild(option);
divclass[0].appendChild(select);
)
}
</script>

How do I populate a select tag when the page loads to only specific select tags?

function populateList(givenID)//givenID from the select tag
{
var select = document.getElementById("givenID"),
listData = ["1","2"];
for(var i = 0; i < listData.length; i++)
//Loops through array and creates a new DOM node and appends array contents to the object
{
var option = document.createElement("OPTION"),
txt = document.createTextNode(listData[i]);
option.appendChild(txt);
option.setAttribute("value",listData[i]);
select.insertBefore(option,select.lastChild);
}
}
<body >
<select id="slt" whenpageloads="populateList">
<!--When the page loads the select tag will be populated -->
<option>
default
</option>
</select>
</body>
You can call onload like Arun has mentioned on body load.
<body onload="populateList('slt')">
or
This will be better choice if you want to load more than one select boxes.
window.onload = function() {
populateList('slt');
};
Apart from that there was one more mistake in your code, as givenID is variable.
var select = document.getElementById(givenID);
instead of
var select = document.getElementById("givenID");
function populateList(givenID)//givenID from the select tag
{
var select = document.getElementById(givenID);
listData = ["1","2"];
for(var i = 0; i < listData.length; i++)
{
var option = document.createElement("OPTION"),
txt = document.createTextNode(listData[i]);
option.appendChild(txt);
option.setAttribute("value",listData[i]);
select.insertBefore(option, select.lastChild);
}
}
window.onload = function() {
populateList('slt');
};
<body>
<select id="slt">
<option>
default
</option>
</select>
</body>

how to bind array data to select option

i have array data it call "provinsi" i got array on console like normal array
here's my code
<select id="select">
<option value="default">default</option>
</select>
<script>
console.log(provinsi)
var select = document.getElementById("select");
for(var i = 0; i < provinsi.length; i++)
{
var option = document.createElement("option"),
txt = document.createTextNode(provinsi[i]);
option.appendChild(txt);
option.setAttribute("value",provinsi[i]);
select.insertBefore(option,select.lastChild);
}
</script>
but i got result like this
here's my console "provinsi"
any suggest ? thanks before
I believe the DOM is not ready yet.
Try putting your code inside IIFE.
(function() {
// the DOM will be available here
console.log(provinsi)
var select = document.getElementById("select");
for(var i = 0; i < provinsi.length; i++)
{
var option = document.createElement("option"),
txt = document.createTextNode(provinsi[i]);
option.appendChild(txt);
option.setAttribute("value",provinsi[i]);
select.insertBefore(option,select.lastChild);
}
})();
** Just to clarify as #karthick mentioned, make sure the script is loaded at the end of the body tag.
I hope this will work happy coding :) Note: change your provinces array with orginal values
$(document).ready(()=> {
let provinces = ["test1", "test2", "test3", "test4" ]
$.each(provinces, function(key,item) {
$("#select").append(new Option(item, key));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select">
<option value="default">default</option>
</select>
The DOM may not have finished loading when your script is run. You should run your function on DOMContentLoaded.
<select id="select">
<option value="default">default</option>
</select>
<script>
var provinsi = ["test1", "test2"];
document.addEventListener("DOMContentLoaded", function(event) {
//DOM fully loaded and parsed
var select = document.getElementById("select");
for(var i = 0; i < provinsi.length; i++)
{
var option = document.createElement("option"),
txt = document.createTextNode(provinsi[i]);
option.appendChild(txt);
option.setAttribute("value",provinsi[i]);
select.insertBefore(option,select.lastChild);
}
});
</script>
<script>
</script>
You can use jquery each function for looping
Javascript Code:
var makers = [
{id: 1, name: 'Toyota'},
{id: 2, name: 'Nissan'},
{id: 3, name: 'Honda'}
]
$.each(makers, function (index, item) {
$('#makers-listing').append(`<option value="${item.id}">${item.name}</option>`);
});
Html Code:
<select id="makers-listing">
<option>Select Maker</option> <!-- This is default value -->
</select>

Drop down menu, directing (depending on answer) to next drop down?

Below is what I currently have. I am now looking to be able to: When they click on artist one it will then take them to another drop down menu where there will be more options about Artist One. And the same if they chose Artist Two etc. Instead of just having an alert.
How would I go about that?
Thank you :)
<form>
<select id="mySelect">
<option value="void">Choose your answer</option>
<option value="artistOne">One</option>
<option value="artistTwo">Two</option>
<option value="artistThree">Three</option>
</select>
</form>
<button id="button" onclick="artist();" type="button">Confirm</button>
Javascript:
function artist() {
var select = document.getElementById("mySelect");
var artist = select.options[select.selectedIndex].value;
if(artist == "artistOne"){
alert("You have chosen Artist One!");
}
else if (artist == "artistTwo"){
alert("You have chosen Artist Two!");
}
}
function artist() {
var select = document.getElementById("mySelect");
var artist = select.options[select.selectedIndex].value;
var newSelectContainer = document.getElementById("artistDetails");
if(artist == "artistOne"){
createArtistSelect(newSelectContainer, ["Artist Detail 1", "Artist Detail 2", "Artist Detail 3"]);
}
else if (artist == "artistTwo"){
createArtistSelect(newSelectContainer, ["Artist2 Detail 1", "Artist2 Detail 2"]);
}
}
function createArtistSelect(elem, options){
//Create and append select list
var dynamicSelect = document.getElementById("dynamicSelect");
if(dynamicSelect)
dynamicSelect.outerHTML = "";
var selectList = document.createElement("select");
selectList.id = "dynamicSelect";
elem.appendChild(selectList);
//Create and append the options
for (var i = 0; i < options.length; i++) {
var option = document.createElement("option");
option.value = options[i];
option.text = options[i];
selectList.appendChild(option);
}
}
If you change your javascript code to this you will generate a drop down menu with the passed options.
You need to change a bit your html:
<form>
<div id="artistDetails">
<select id="mySelect">
<option value="void">Choose your answer</option>
<option value="artistOne">One</option>
<option value="artistTwo">Two</option>
<option value="artistThree">Three</option>
</select>
</div>
</form>
<button id="button" onclick="artist();" type="button">Confirm</button>
I created a function that is called on the onChange of the select (you can change it to be on the onClick of the input)
var details1 = ["1-1", "1-2", "1-3"];
var details2 = ["2-1", "2-2", "2-3", "2-4"];
var details3 = ["3-1", "3-2"];
function CreateCmb(artist) {
var cmbDetails = document.getElementById('cmbDetails');
if (cmbDetails !== null) {
while (cmbDetails.options.length > 0)
cmbDetails.remove(0);
} else {
cmbDetails = document.createElement("select");
cmbDetails.id = "cmbDetails";
body.appendChild(cmbDetails);
}
var currentDetails = [];
if (artist === "artistOne") currentDetails = details1;
else if (artist === "artistTwo") currentDetails = details2;
else if (artist === "artistThree") currentDetails = details3;
for (var i = 0; i < currentDetails.length; i++) {
var option = document.createElement("option");
option.text = currentDetails[i];
option.value = currentDetails[i];
cmbDetails.appendChild(option);
}
}
How it works:
First it get the dynamic select, then check if he is NOT null (is created). If this is the case, it delete all the option. If the select is null (not yet created), it create it and place it in the body.
Then it check wich details he need to show (the if else if block).
To finish, I looped the details and create the new options.
The nice part about this is that you will always have only one dynamic select because if he already exist, he reuse it ! That allow you to manually create and place it somewhere and he will use it if he have the correct id (in this case 'cmbDetails')
See this FIDDLE for an example !

How would I dynamically create input boxes on the fly?

I want to use the value of a HTML dropdown box and create that number of input boxes underneath. I'm hoping I can achieve this on the fly. Also if the value changes it should add or remove appropriately.
What programming language would I need to do this in? I'm using PHP for the overall website.
Here is an example that uses jQuery to achieve your goals:
Assume you have following html:
<div>
<select id="input_count">
<option value="1">1 input</option>
<option value="2">2 inputs</option>
<option value="3">3 inputs</option>
</select>
<div>
<div id="inputs"> </div>
And this is the js code for your task:
$('#input_count').change(function() {
var selectObj = $(this);
var selectedOption = selectObj.find(":selected");
var selectedValue = selectedOption.val();
var targetDiv = $("#inputs");
targetDiv.html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
You can simplify this code as follows:
$('#input_count').change(function() {
var selectedValue = $(this).val();
var targetDiv = $("#inputs").html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
Here is a working fiddle example: http://jsfiddle.net/melih/VnRBm/
You can read more about jQuery: http://jquery.com/
I would go for jQuery.
To start with look at change(), empty() and append()
http://api.jquery.com/change/
http://api.jquery.com/empty/
http://api.jquery.com/append/
Doing it in javascript is quite easy. Assuming you've got a number and an html element where to insert. You can obtain the parent html element by using document.getElementById or other similar methods. The method assumes the only children of the parentElement is going to be these input boxes. Here's some sample code:
function addInput = function( number, parentElement ) {
// clear all previous children
parentElement.innerHtml = "";
for (var i = 0; i < number; i++) {
var inputEl = document.createElement('input');
inputEl['type'] = 'text';
// set other styles here
parentElement.appendChild(inputEl);
}
}
for the select change event, look here: javascript select input event
you would most likely use javascript(which is what jquery is), here is an example to show you how it can be done to get you on your way
<select name="s" onchange="addTxtInputs(this)" onkeyup="addTxtInputs(this)">
<option value="0">Add</option>
<option value="1">1</option>
<option value="3">3</option>
<option value="7">7</option>
</select>
<div id="inputPlaceHolder"></div>
javascript to dynamically create a selected number of inputs on the fly, based on Mutahhir answer
<script>
function addTxtInputs(o){
var n = o.value; // holds the value from the selected option (dropdown)
var p = document.getElementById("inputPlaceHolder"); // this is to get the placeholder element
p.innerHTML = ""; // clears the contents of the place holder each time the select option is chosen.
// loop to create the number of inputs based apon `n`(selected value)
for (var i=0; i < n; i++) {
var odiv = document.createElement("div"); //create a div so each input can have there own line
var inpt = document.createElement("input");
inpt['type'] = "text"; // the input type is text
inpt['id'] = "someInputId_" + i; // set a id for optional reference
inpt['name'] = "someInputName_" + i; // an unique name for each of the inputs
odiv.appendChild(inpt); // append the each input to a div
p.appendChild(odiv); // append the div and inputs to the placeholder (inputPlaceHolder)
}
}
</script>

Categories