Populating a form with names from a .txt file - javascript

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>

Related

if statement is not doing anithing when option is selected JS

I have a script that creates options in select and another script that should write test in console when I'm choosing electro option. But It's not working.
scripts:
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', (event) => {
function addOption() {
var optionArr = ['-', 'eletro', 'auto'];
var select = document.getElementsByName('butterbean_stm_car_manager_setting_autofilling')[0];
for(var i=0; i<optionArr.length; i++){
var opt = document.createElement('option');
opt.text = optionArr[i];
opt.value = optionArr[i];
select.add(opt);
}
}
addOption();
});
</script>
<script type="text/javascript">
let autofilling = document.getElementsByName('butterbean_stm_car_manager_setting_autofilling').value;
if(autofilling == 'eletro'){
console.log('test');
};
</script>
THERE IS NO CONSOLE ERRORS

Javascript. Change a form option based on a previous one

I'm trying to change the options that appear in my select box named session when a certain option is picked in my select box named movie.
Here's the script I've got so far.
<script>
var optionList = document.getElementsByName("movie")[0];
var movieList = ["AC", "CH", "AF", "RC"];
for(var i = 0; i < movieList.length; i++){
var movie = movieList[i];
var option = document.createElement("option");
option.textContent = movie;
option.value = movie;
optionList.appendChild(option);
}
</script>
<script>
var sessionList = document.getElementsByName("session")[0];
var actionSession = ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"];
var childrenSession = ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"];
var foreignSession = ["MON-06", "TUE-06", "SAT-06", "SUN-06"];
var romanticSession = ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"];
if(document.getElementsByName("movie")[0].value === movieList[0])
{
for(var i = 0; i < actionSession.length; i++){
var session = actionSession[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionList.appendChild(option);
}
}
</script>
Consider changing the Sessions to an object, like so:
var sessions = {
"AC": ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"],
"CH": ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"],
"AF": ["MON-06", "TUE-06", "SAT-06", "SUN-06"],
"RC": ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"]
}
This way, you can use the onchange of your select tag to get the value of the selected option and reference the list of sessions for the appropriate movie list as such:
var category = document.getElementByName("movie").value;
var currentSession = sessions[category];
for(var i = 0; i < currentSession.length; i++){
var session = currentSession[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionList.appendChild(option);
}
Objects in javascript can be referenced as "key" => "value" pairs simply by following the syntax:
object = { "key": value }, and value's type can be anything - even another Object!
You can even declare object keys like such:
var sessions = {};
sessions['AC'] = [...];
sessions['CH'] = [...];
sessions.AF = [...];
sessions.RC = [...];
That's right - all of the above declarations can be referenced as sessions['xx']
Hope this simplifies things a bit.
You could create a dictionary mapping elements of movieList to lists of <option> elements, maybe?
You might call the dictionary sessionOptions. You would then change all the children of #session at once - so this would go in your onchange handler for sessionList:
var sessionList = document.getElementsByName("session")[0];
var chosenMovie = "..."; // "AC", for instance
// Remove all elements from sessionList
while(sessionList.firstChild) {
sessionList.removeChild(sessionList.firstChild);
}
// Add the chosen movie options
var chosenMovieOptions = sessionOptions[chosenMovie];
for(var i = 0; i < chosenMovieOptions.length; i++) {
sessionList.appendChild(chosenMovieOptions[i]);
}
You would also want to make a mapping of movie codes to session lists:
var SESSION_LISTS = {
"AC": ["WED-09", "THU-09", "FRI-09", "SAT-09", "SUN-09"],
"CH": ["MON-01", "TUE-01", "WED-06", "THU-06", "FRI-06", "SAT-12", "SUN-12"],
"AF": ["MON-06", "TUE-06", "SAT-06", "SUN-06"],
"RC": ["MON-09", "TUE-09", "WED-01", "THU-01", "FRI-01", "SAT-06", "SUN-06"]
};
Then, to build sessionOptions, for each "session string list" (such as actionSession), you would loop through the session list and create elements:
var currentSession = "..."; // currentSession is the current session list - "AC", for instance
var currentSessionOptions = SESSION_LISTS[currentSession];
sessionOptions[currentSession] = [];
for(var i = 0; i < currentSessionOptions.length; i++){
var session = currentSessionOptions[i];
var option = document.createElement("option");
option.textContent = session;
option.value = session;
sessionOptions[currentSession].append(option);
}
But then you would do this for every sublist in SESSION_LISTS, so you would put this code in some initializer function:
var sessions = Object.keys(SESSION_LISTS);
for(var i = 0; i < sessions.length; i++) {
currentSession = sessions[i];
// the code snippet above
}

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

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/

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