Use associative Javascript arrays to populate dropdown, then fill text box - javascript

I'm new to Javascript (but fairly proficient in php) and I'm trying to use a set of associative arrays to perform two tasks.
First: Populate a dropdown menu (this part is working)
var select = document.getElementById('FName');
var options = fNames;
for(var i = 0; i < (options.length-1); i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
The 'fNames' variable is an array with a list of strings which I've taken from a php array. I have another array, called 'fDesc' which is indexed to match the 'fNames' array. Something like this:
var fNames = ["aName", "bName", "cName"]
var fDesc = ["aDesc", "bDesc,", "cDesc"]
They're currently separate arrays, not a single multidimensional one.
How can I make "aDesc" appear in a text box when "aName" is selected from the pulldown menu?

First of all, the for element is population less elements, you should remove the -1 of (options.length-1)
Then you need to asociate a handler event for select.onchange and use index of to retrieve the index of the array.
HTML:
<select id='FName'></select>
<input id='AName' type='text'/>
JS:
var fNames = ["aName", "bName", "cName"];
var fDesc = ["aDesc", "bDesc,", "cDesc"];
var select = document.getElementById('FName');
var options = fNames;
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);
}
select.onchange = function(){
var textbox = document.getElementById('AName');
textbox.value = fDesc[fNames.indexOf(select.value)];
}
JsFiddle:
http://jsfiddle.net/dBtUz/

better put aName as text and aDesc as value.
HTML
<select id='FName' onchange='fillText()'></select>
<input id='Fdesc' type='text'/>
Javascript
window.onload = function(){
var fNames = ["aName", "bName", "cName"]
var fDesc = ["aDesc", "bDesc", "cDesc"]
var select = document.getElementById('FName');
for(var i = 0; i < (fNames.length); i++) {
var el = document.createElement("option");
el.textContent = fNames[i];
el.value = fDesc[i];
select.appendChild(el);
}
select.selectedIndex = -1;
}
function fillText(){
document.getElementById('Fdesc').value = document.getElementById('FName').value;
}

You need to search the index of the selected value and then you get with that index the same position in your search array.
Updated Solution also with manual fill:
<script>
document.addEventListener('DOMContentLoaded', onDomContentLoaded);
// data
var fNames = ["aName", "bName", "cName"];
var fDesc = ["aDesc", "bDesc", "cDesc"];
function onDomContentLoaded() {
var mySelect = document.getElementById("mySelect");
fillSelect(mySelect);
mySelect.addEventListener('change', onSelectChange);
}
function fillSelect(mySelect) {
for(var i = 0; i < (fNames.length); i++) {
var opt = fNames[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
mySelect.appendChild(el);
}
}
function onSelectChange(){
var selectedValue = this.options[this.selectedIndex].value;
//console.log('selected value', selectedValue);
var selectedValueIndexInArray = fNames.indexOf(selectedValue);
var fieldOutput = document.getElementById("output");
fieldOutput.innerHTML = fDesc[selectedValueIndexInArray];
}
</script>
<select id="mySelect"></select>
<div id="output"></div>
Working Example
http://jsfiddle.net/x92ka/4/

Related

Populating a form with names from a .txt file

I am trying to populate a dropdown list with a bunch of names that are stored in a .txt in the same directory as the HTML code. Each name is on a new line of this file and"names" is the id of the dropdown that will store the names.
Upon loading the page, the list is not populated at all. Any guidance would be awesome.
<script type = "text/javascript">
window.onload = function () {
var select = document.getElementById("names");
var textFile = "/names.txt";
jQuery.get(textFile, function(textFileData) {
var EachLineInTextFile = textFileData.responseText.split(",");
for (var i = 0, len = EachLineInTextFile.length; i < len; i++) {
var option = document.createElement('option');
option.text = option.value = EachLineInTextFile[i];
select.add(option, 0);
};
};
};
</script>
Thanks!
It looks like the major issue was that I needed a better version of jquery. Thank you everyone for your help!
<script type = "text/javascript">
window.onload = function () {
var select = document.getElementById("names");
var textFile = "/names.txt";
jQuery.get(textFile, function(textFileData) {
window.alert(textFileData);
var EachName= textFileData.split("\n");
for (var i = 0, len = EachName.length; i < len; i++) {
var option = document.createElement('option');
option.text = option.value = EachName[i];
select.add(option, 0);
};
});
};
</script>

Best way to create new DOM elements using Jquery

is it better to create a DOM element like this:-
var option='';
var objY = $('select[name="yaxis"]');
for(var key in summaryObj)
{
option += '<option value="'+summaryObj[key]+'">'+key+'</option>';
}
objY.html(option);
or like this,
var objY = $('select[name="yaxis"]');
var option = document.createElement("option");
for(var key in summaryObj)
{
var san = summaryObj[key];
objY.append($(option).clone().attr({value:san,text:key}));
}
For perfomance, this is probably among the fastest ways
var option = document.createElement("option");
var frag = document.createDocumentFragment();
for (var key in summaryObj) {
var clone = option.cloneNode();
clone.value = san;
clone.innerHTML = key;
frag.appendChild(clone);
}
$('select[name="yaxis"]').append(frag);
For readability, I like this
var objY = $('select[name="yaxis"]');
var frag = [];
$.each(summaryObj, function(key, val) {
frag.push(
$('<option />', {
value : san,
text : key
})
);
});
objY.append(frag);
In jQuery, you Do it like this:
var select = $('<select>').attr('name','yaxis');
var option = $("<option>");
option.text('word').value('word');
select.append(option);

Cannot read property 'value' of null from HTML input

I have fixed it already. I cannot figure it our why am I getting "Uncaught TypeError: Cannot read property 'value' of null"? The error shows up on the "var name = document.getElementById("name").value;" line.
var colors = [];
function Save() {
var name = document.getElementById("name").value;
var rgb = document.getElementById("colordisplay").innerHTML;
var opacity = document.getElementById("div").style.opacity;
colors.push({
name_prop:name,
rgb_prop:rgb,
opacity_prop:opacity,
});
//pass the array into the dropdown list
var select = document.getElementById("selectColor");
for (var i = 0; i < colors.length; i++) {
var opt = colors[i];
var el = document.createElement("option");
el.innerHTML = opt;
el.value = opt;
select.appendChild(el);
console.log(colors);
}
}
Insert function is not called anywhere in your JSBin

hr tag in javascript

I am working on phonegap and I am new to it. I want to draw a line using hr under the menu items which are displayed. but unfortunately I am unable to do so.
if somebody can help in this regard. Thanks in advance.
here is the code snippet
{
success:function(res,code) {
entries = [];
var xml = $(res);
var items = xml.find("item");
$.each(items, function(i, v) {
category1.push($(v).find("category").text());
/* $("#status").append("menu_type <b>"+menu_type+"</b><br/>"); */
console.log( "PRICE" + ": " + $(v).find("menu_type").text() );
});
var category = category1.unique();
var select = document.getElementById("selectNumber");
for(var i = 0; i < category.length; i++) {
var el1 = document.createElement("li");
var opt = category[i];
var el = document.createElement("a");
el.textContent = opt;
el.value = opt;
el1.appendChild(el);
select.appendChild(el1);
}
}
Try adding something like this
document.getElementById("ElementBelowWhichHRShouldCome").appendChild(document.createElement('hr'));
Try innerHTML. Here is an example:
http://jsfiddle.net/Wxv6n/
var doc = document;
var get = function(id){return doc.getElementById(id);};
get("foo").innerHTML = '<hr/>';
..and don't forget to cache your references to document
After Every Menu Item,you can use this.Its pretty simple.
$("#menu_item").after('<hr/>');
after() in jquery
DEMO FIDDLE

How do I populate a select box automatically with values from a IndexedDB objectStore?

I would like to iterate over a IndexedDB objectStore, get the results and populate this select box.
This is my HTML
<tr>
<td>
<select id="opt" name="opt"></select>
</td>
</tr>
This is my JavaScript
function populateOptions() {
var options = [ "1", "2", "3", "4", "5"];
var opt = document.getElementById("opt");
for (var i = 0; i < options.length; i++) {
var option = document.createElement("option");
option.value = options[i];
var optionText = document.createTextNode(options[i]);
option.appendChild(optionText);
opt.appendChild(option);
}
}
populateOptions();
Try the following:
var dbreq = indexeddb.open("db");
dbreq.onsuccess = function (conn){
var trans = dbreq.result.transaction(["objectstore"]);
var obj = trans.objectStore("objectstore");
var cursor = obj.openCursor();
cursor.onsuccess = function (e) {
if (!cursor.result) {
var opt = document.getElementById("opt");
var option = document.createElement("option");
option.value = cursor.result.value;
var optionText = document.createTextNode(cursor.result.value);
option.appendChild(optionText);
opt.appendChild(option);
cursor["continue"]()
} else {
// cursor ended
}
}
Or use my linq2indexeddb library and do it like this:
var db = linq2indexedDB("db");
db.linq.from("objectstore").select.then(null, null, function(e){
var opt = document.getElementById("opt");
var option = document.createElement("option");
option.value = e.data;
var optionText = document.createTextNode(e.data);
option.appendChild(optionText);
opt.appendChild(option);
});
for more information about indexeddb I can reffer to my blog. Here I frequently post information about the indexedDB API.
In html :
<body onload="load()">
In javascript :
function load(){
populateOptions();
}
or shortly :
<body onload="populateOptions()">

Categories