how to bind array data to select option - javascript

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>

Related

Linked drop down menus

I am trying to create 2 drop down menus, where the first list is linked to the second list (the second list is updated each time I select something in the first one).
I have some code that works, but it seems a little bit confusing to me.
Also this is working only if the script is in the body. If I move it to the head it doesnt work.
Why?
Can the same thing be implemented in some other way for example with the use of a 2d array, with the use on only Javascript?
var sel1 = document.querySelector('#sel1');
var sel2 = document.querySelector('#sel2');
var options2 = sel2.querySelectorAll('option');
function giveSelection(selValue) {
sel2.innerHTML = '';
for (var i = 0; i < options2.length; i++) {
if (options2[i].dataset.option === selValue) {
sel2.appendChild(options2[i]);
}
}
}
giveSelection(sel1.value);
<h1><b>Title</b></h1>
<select id="sel1" onchange="giveSelection(this.value)">
<option value="0"></option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="sel2">
<option data-option="a">apple</option>
<option data-option="a">airplane</option>
<option data-option="b">banana</option>
<option data-option="b">book</option>
</select>
Yes... It should not work. because when the script is in the head section. #self1 object and the #sel2 DOM elements are not on the DOM when it executes. when It's in the body section DOM elements are created on the DOM. one way to make it work is to bring those element referencing variables inside of the function as below.
function giveSelection(selValue) {
var sel1 = document.querySelector('#sel1');
var sel2 = document.querySelector('#sel2');
var options2 = sel2.querySelectorAll('option');
sel2.innerHTML = '';
for (var i = 0; i < options2.length; i++) {
if (options2[i].dataset.option === selValue) {
sel2.appendChild(options2[i]);
}
}
}
And believe me, It is not an efficient way. It's a best practice to include javascript to the bottom of the page and CSS to the top of the page. Including your script in the bottom of the body section is alright.
In order to use that script from head section you need to use window.onload that will fired when the DOM is ready.
In your case you can do something like that:
<head>
<script>
const load = () => {
sel1 = document.querySelector('#sel1');
sel2 = document.querySelector('#sel2');
options2 = sel2.querySelectorAll('option');
giveSelection(sel1.value);
}
function giveSelection(selValue) {
sel2.innerHTML = '';
for (var i = 0; i < options2.length; i++) {
if (options2[i].dataset.option === selValue) {
sel2.appendChild(options2[i]);
}
}
}
window.onload = load;
</script>
</head>
codepen

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 Dynamically Create <option> elements within a parent <optgroup>

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>

drop down list items taken from the java script

<select id="myList" onchange="favBrowser()">
<option> var x</option>
<option> var y</option>
</select>
<script>
var x="google"; var y="firefox";
</script>
my question is , how to take the option's values from javascript
i think he ment he want to fill the options by Script
this can be done by
<select id="myDropdown">
</select>
<script type="text/javascript">
function fillDropDown() {
var ddl = document.getElementById('myDropdown');
for (var i = 1; i < 50; i++) {
var myNewOption = new Option();
myNewOption.value = i;
myNewOption.text = "my " + i.toString() + " option...";
ddl.options.add(myNewOption);
}
}
fillDropDown();
</script>
Cheers.
You can get it by writing
function favBrowser(){
var sel = document.getElementById("myList");
var value =sel.options[sel.selectedIndex].value;
window.alert(value);
}
You need to supply more information about what it is you really want to do. If what you want is to take the selected value, then take a look at this question
Get selected value in dropdown list using JavaScript?

Updating Selectbox options

I have 2 Selectbox
Countrynames
Airports
And as I select a countryname in first selectbox an Ajax request will be sent and it returns a list of Airposts as options like
"
<option value='1'>abc
<option value='3'>lmn
<option value='2'>xyz
"
now i have to replace only the options of select tag.
i am trying to do something like
var country_select = document.getElementById("country_select");
country_select.options.length = 0;
country_select.options = response.responseText
but this assignment is not working how may i get it done!
Try
var country_select = document.getElementById("country_select");
country_select.innerHTML = response.responseText;
This is a little bit more tricky, you won't be able to do it using innerHTML or anything like that.
You will have to change the way your ajax is returning airport names. Instead of <option>abc</option><option>xyz</option> return a string of names seperated by for example || : abc||def||xyz . then explode the string into an array in JS, create an option elements from every element in array, and add it to dropdown. check that:
<html>
<head>
<script>
var ajaxResponse = "abs||def||xyz||test||blah";
function updateOptions( optionsString )
{
var options = optionsString.split("||");
for( var i=0; i< options.length; i++ )
{
AddItem( options[i], options[i] );
}
}
function AddItem(Text,Value)
{
var opt = document.createElement("option");
opt.text = Text;
opt.value = Value;
document.getElementById("mydropdown").options.add(opt);
}
function removeOptions()
{
document.getElementById('mydropdown').length = 0;
}
</script>
</head>
<body>
<input type="button" onclick="updateOptions(ajaxResponse)" value="update"></input>
<input type="button" onclick="removeOptions()" value="remove"></input>
<select id="mydropdown">
</select>
</body>
</html>

Categories