populating html with javascript array - javascript

I am trying to populate html select with javascript array, can you guys help me make this one work below are my codes
external javascript (I have found this code somewhere in the internet)
function setRuleName()
{ var myCars=new Array("Saab","Volvo","BMW");
var sel = document.getElementById("dropping") // find the drop down
for (var i in myCars)
{ // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = title[i]; // set the value
opt.text = title[i]; // set the text
sel.appendChild(opt); // add it to the select
}
}
html code
<Select onclick="setRuleName();" id="dropping" >
</Select>

Not sure where your title attribute came from, but when looping an array, use a standard for, not a for in
for (var i = 0; i < myCars.length; i++) {
var opt = document.createElement("option"); // Create the new element
opt.value = myCars[i]; // set the value
opt.text = myCars[i]; // set the text
sel.appendChild(opt); // add it to the select
}

Alternative ways to write this code.
function setRuleName(){
var myCars=["Saab","Volvo","BMW"],
sel=document.getElementById("dropping");
for(var a=0,tit;tit=myCars[a];++a){
var opt=document.createElement("option");
opt.value=opt.textContent=tit;
sel.appendChild(opt);
}
}
For internal use (NO POST)
function setRuleName(){
document.getElementById("dropping").innerHTML='<option>'+
["Saab","Volvo","BMW"].join('</option><option>')+
'</option>';
}
to access the value :
console.log(document.getElementById("dropping").selected.textContent);

Related

Drop down menu with array, define value of each option

Hello there Stackoverflow!
Today I tried making a drop-down menu with an array. It did work, but the problem that has taken place after this, is to define the values printed by the array.
As of now, this is the code regarding the drop-down menu.
HTML
<select id="selectDestinasjon">
<option>Velg ett sted</option>
</select>
Javascript
var select = document.getElementById("selectDestinasjon");
var options = ["Konsberg", "Trysil", "Beitostølen"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
But I want to give each option a value, that I can later impliment into a calculator, because I want to make a booking service where each of these options has different value and the calculator retrieve info from current selected option, setting a price depending on selected option.
If anything seem unclear or too little detailed, please ask and I'll do my best to explain.
JSFIDDLE
https://jsfiddle.net/a3pe6zcu/
Are you looking for something like this? I have updated your data to hold the price and the name of the place. Now the select has the text as the place and the price as the value. Updated fiddle
var select = document.getElementById("selectDestinasjon");
var options = [{"place": "Konsberg","price":"$20"}, {"place":"Trysil","price":"$30"}, {"place":"Beitostølen","price":"$40"}];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt.place;
el.value = opt.price;
select.appendChild(el);
}

How to populate a drop down list in HTML5 using javascript?

I want to fetch data from web service, and populate that into a drop down list.
My code is as given below. A drop down is created but data cannot be populated. Please suggest me with some code.
function jsondata(data)
{
alert("JSONdata");
var parsedata=JSON.parse(JSON.stringify(data));
var captain_details=parsedata["Captain Details"];
var drop_down=document.getElementById("captainlist");
var drop=document.createElement("select");
for(var i=0;i<captain_details.length;i++)
{
var captain = captain_details[i];
captain_name=captain['Captain Name'];
alert(captain_name);
document.getElementById("captainlist").appendChild(drop);
drop.add(captain_name,null);
}
}
According to https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement drop.add expects an HTMLElement, not a string of text.
http://jsfiddle.net/vPUmX/
var data = [
{ name: "Mal Reynolds" },
{ name: "Piet Heyn" },
{ name: "Jean-Luc Picard" }
];
var elm = document.getElementById("captains"); // elm is a <select> element
for (var i = 0, len = data.length; i < len; i++) {
var name = data[i].name;
// create an option element
var option = document.createElement("option");
option.value = i;
option.textContent = name;
// add option
elm.add(option);
}
drop in this case is <select> node not <option> node --> document.getElementById("captainlist").appendChild(drop); You should create <option> node set up its value and text and add it into <select> element. I assume drop_down in var drop_down=document.getElementById("captainlist"); points to <select> node

Append multiple options in html select at once

I want to append multiple options in html select.
Currently I'm using the below code in a loop, but it make the working slow as it have to add new option every time.
Code Snippet:
s.options[s.options.length]= new Option(url, '1');
So I guess, if I can add all the options at once and not one by one like above, maybe it can make it little faster.
Please suggest a more fast function then this one. Thanks
Try this,
s.options[s.options.length]=function Option(url,'1') {
// statements go here
};
You may be able to do it with a DocumentFragment but I'm unsure about browser support. It certainly works in current versions of all browsers (including IE 10) but I doubt it works in old IE.
var frag = document.createDocumentFragment();
for (var i = 0; i < 10; ++i) {
var option = document.createElement("option");
option.value = "" + i;
option.text = "Option " + i;
frag.appendChild(option);
}
s.appendChild(frag);
Demo: http://jsfiddle.net/QsNpe/
Try this:
var tmpOptions = [];
for(var i=0; i<optionsLength; i++) {
tmpOptions[i] = new Option(url, i);
}
s.options = tmpOptions;
try this
var dataArr = [{'value':'val1','text':'text1'},
{'value':'val2','text':'text2'},
{'value':'val3','text':'text3'},
{'value':'val4','text':'text4'},
{'value':'val5','text':'text5'},
{'value':'val6','text':'text6'},
{'value':'val7','text':'text7'}];
// Removes all options for the select box
$('#optExample option').remove();
// .each loops through the array
$.each(dataArr, function(i){
$('#optExample').append($("<option></option>")
.attr("value",dataArr[i]['value'])
.text(dataArr[i]['text']));
});

IE removes option tags created with javascript

So I have this following code that works great for every browser I've tested so far, except IE
var array = eval( '(' + xmlHttp.responseText + ')' );
var html = '';
for(var key in array)
{
html += '<option value="' + key + '">' +array[key] + '</option>';
}
alert(html);
document.getElementById('countries').innerHTML = html;
The problem stands at the .innerHTML. The alert prints the data as it should be, but the inner strips the tag and I end up with words in a row.
So, any ideas how to possibility fix that issue?
It's a known issue that IE doesn't let you use .innerHTML to set option elements in a select.
You should be creating elements using DOM methods instead.
var fragment = document.createDocumentFragment();
for(var key in array) {
var opt = fragment.appendChild(document.createElement("option"));
opt.value = key;
opt.text = array[key];
}
document.getElementById('countries').appendChild(fragment);
And if array is an actual Array, then use for instead of for-in in JavaScript.
And if you need to empty the select first, you can do that with .innerHTML = "", or better, with a loop:
var sel = document.getElementById('countries');
while (sel.firstChild)
sel.removeChild(firstChild);
sel.appendChild(fragment);
var select = document.getElementById('countries'); // assuming this is your <select>
for (var key in array) {
var option = document.createElement('option');
option.value = key;
option.text = array[key];
select.appendChild(option);
}

Javascript helper method for generating select tag based on provided values

I am trying to create a helper method in my JS toolkit that looks like this
var selectOptionValues = [" ","NA","Yes","No"];
var selectedValue = "No";
function CreateSelectList(selectId,selectOptionValues,selectedValue){
// build the selectlist
// if the selectedValue is not null make this value selected
// return select tag
}
I am tried to do something like selectedOption = selectTag[selectedValue] and then selecteOption.selected = true but its not working.
Assuming you're generating option by creating DOM nodes and the part that isn't working, is the selected state of the No option. Try selectOption.setAttribute("selected","selected") - roughly...
var selectOptionValues = [" ","NA","Yes","No"], selectedValue = "No";
function CreateSelectList(selectId,selectOptionValues,selectedValue){
var selectList = document.createElement("select"), selectOption;
for (var i=0, totalOptions = selectOptionValues.length; i < totalOptions ; i++) {
selectOption = document.createElement("option");
selectOption.value = selectOptionValues[i];
selectOption.innerText = selectOptionValues[i];
if (selectOptionValues[i] == selectedValue) {
selectOption.setAttribute("selected","selected");
}
selectList.appendChild(selectOption);
};
return selectList;
}
In addition to method Dean Burge suggested, you can also set the default value by selectedIndex property of select object. If you make selectedValue the index of desired value, it becomes pretty simple:
//selectedValue==3;
yourPopulatedSelect.selectedIndex=selectedValue;
//"No" will be selected

Categories

Resources