Any ideas on what is wrong with this javascript code? - javascript

I have the code below. The purpose of the code is to grab all the values stored in the local storage and display them in two HTML elements with ids of 'title' and 'textLoc'. 'title' is an <input type="text"> and 'textLoc' is a <textarea>. I want the values to be stored in the <textarea> and the keys to be stored in the <input type="text">. The values are being stored correctly but the keys are not. Any ideas on why this would be?
var tests = [];
var titles = [];
var finalTests = "";
var key, value;
for (var i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
value = localStorage.getItem(key);
tests.push(value);
titles.push(key);
finalTests += "<tr><td><a class=\"dashlinks\" href=\"javascript:void\" onclick=\"rememberTest("+i+")\">" + key + "</a></td></tr>";
}
for (i=0; i<tests.length; i++) {
document.getElementById('title').innerHTML = titles[i];
document.getElementById('textLoc').innerHTML = tests[i];
}

You should use document.getElementById('title').value and document.getElementById('textLoc').value. Also it seems like you are doing nothing with finalTests after you store it.

You should be appending the string to the text area:
document.getElementById('title').innerHTML = document.getElementById('title').innerHTML + titles[i] + '\n';

Related

How do I dynamically change a key in a for loop

I want to be able to change the key in a for loop, it's hard to explain what I need so I made a demo based on the https://www.w3schools.com/js/tryit.asp?filename=tryjs_loop_for play ground.
I need to be able to swap the keys depending on logic because the array data keys will alter depending on the json feed therefore it won't be possible to hard code the keys.
Thanks in advance
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
<p id="demo"></p>
<script>
var cars = [{"name":"BMW", "colour":"blue"}, {"name":"Volvo",
"colour":"green"}, {"name":"Saab", "colour":"pink"}, {"name":"Ford",
"colour":"grey"}, {"name":"Fiat", "colour":"yellow"}, {"name":"Audi",
"colour":"silver"}];
var text = "";
var i;
for (i = 0; i < cars.length; i++) {
var keyToChoose = "name"; /// or I could choose "colour"
text += cars[i].keyToChoose + "<br>"; /// how do I dynamically change 'keyToChoose'?
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
You use it like this.
text += cars[i][keyToChoose] + "<br>";
now it depends on the value of the variable keyToChoose.
You can use a global variable to decide your key.
<script>
// 1 = name , 2 = colour
var currentKey = 1;
var cars = [{"name":"BMW", "colour":"blue"}, {"name":"Volvo",
"colour":"green"}, {"name":"Saab", "colour":"pink"}, {"name":"Ford",
"colour":"grey"}, {"name":"Fiat", "colour":"yellow"}, {"name":"Audi",
"colour":"silver"}];
var text = "";
var i;
for (i = 0; i < cars.length; i++) {
// the key is chosen based on the currentKey which can be made a global variable and changed dynamically.
var keyToChoose = currentKey === 1 ? "name" : "colour";
text += cars[i].keyToChoose + "<br>"; /// how do I dynamically change 'keyToChoose'?
}
document.getElementById("demo").innerHTML = text;
</script>

Ignoring ' from javascript code, SQLite

I have a french category named piqûres d'insectes that I am pulling from a SQLite database. Unfortunately, the ' in the category keeps breaking my javascript code, as seen in my pictures where it turns my breadcrumbs into undefined (half the word is missing as well clearly from the apostrophe). Is there a way I can pull this as just text so it does not break my code?
Javascript:
function txSuccessListAddSymptoms(tx,results) {
//console.log("Read Additional Symptoms success");
var category = getUrlVars().category;
var mainsymptom = getUrlVars().mainsymptom;
var len = results.rows.length;
var addSymp;
for (var i=0; i < len; i = i + 1) {
addSymp = results.rows.item(i);
};
$('#addSymps').listview('refresh');
}
You can use an escape character: \'
So for example try to use: piqûres d\'insectes
You can use the original name by adding this lines of code:
var str = getUrlVars().category;
var category = str.replace("'", "\'");
This code changes the ' to \' if it is in the name.
I hope this helped for you
EDIT::
Soo.. this would be your script:
function txSuccessListAddSymptoms(tx,results) {
//console.log("Read Additional Symptoms success");
var str = getUrlVars().category;
var category = str.replace("'", "\'");
var mainsymptom = getUrlVars().mainsymptom;
var len = results.rows.length;
var addSymp;
for (var i=0; i < len; i = i + 1) {
addSymp = results.rows.item(i);
};
$('#addSymps').listview('refresh');
}

Getting array from text

I have been experimenting with this code http://mounirmesselmeni.github.io/2012/11/20/javascript-csv/ to get data from a text file. (Working demo here: http://mounirmesselmeni.github.io/html-fileapi/).
It works well for reading files, but I am stumped about how to get the data into an array. It seems as though it is reading everything into the "lines" array, but I can't work out how to use it.
I tried modifying it like this:
function processData(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var lines = [];
var myArray = [];
while (allTextLines.length) {
lines.push(allTextLines.shift().split(','));
myArray.push(allTextLines.shift().split(',')); //put data into myArray
}
function myFunction() { //display myArray in "demo"
var index;
for (index = 0; index < myArray.length; index++) {
text += myArray[index];
}
document.getElementById("demo").innerHTML = text;
}
but that didn't work. I know I am missing something simple here, but this has me stumped.
Currently you modify the array twice:
lines.push(allTextLines.shift().split(',')); // shift modifies the array
myArray.push(allTextLines.shift().split(',')); //gets the shifted array
You might want to try putting this in temp variable:
var line = allTextLines.shift().split(',');
lines.push(line);
myArray.push(line);
Try
csv.split(/\r\n|\n|,/).map(function(value, index) {
demo.innerHTML += "\n" + value.trim()
});
var csv = 'Year,Make,Model,Description,Price'
+ '1997,Ford,E350,"ac, abs, moon",3000.00'
+ '1999,Chevy,"Venture ""Extended Edition""","",4900.00'
+ '1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00'
+ '1996,Jeep,Grand Cherokee,"MUST SELL!'
+ 'air, moon roof, loaded",4799.00',
demo = document.getElementById("demo");
csv.split(/\r\n|\n|,/).map(function(value, index) {
demo.innerHTML += "\n" + value.trim()
})
<div id="demo"></div>

appending values to textbox using for loop javascript

I am trying to add values to a textbox when looping through an array when checking checkboxes but as it is at the moment getting undefined.
Advice perhaps as to why the values are 'undefined'
var txtBoxValues = [];
$(document).on("click", "input[name=chkRelatedTopics]", function () {
var nameAdminUser = $(this).val();
var txtBox = document.getElementById("txtTraningTopics");
txtBox.value = '';
txtBoxValues.push(nameAdminUser);
for (var i in txtBoxValues) {
var str = txtBoxValues[i].value;
txtBox.value += str + '; ';
}
});
nameAdminUser is already a string, so don't take .value from it.
You could replace
var str = txtBoxValues[i].value;
with
var str = txtBoxValues[i];
But instead of using this loop, and assuming you don't want, as I suppose, the last ";", you could also do
txtBox.value = txtBoxValues.join(';');
nameAdminUser seems to be a String and in your for loop you expect an object. What if you simply do:
for (var i in txtBoxValues) {
var str = txtBoxValues[i];
txtBox.value += str + '; ';
}

Changing radio buttons name using Javascript

I'm using a simple JS duplicate function to duplicate a div. Inside is form information with radio buttons, including one group called 'getOrRequest'. Each div represents a book and needs to have its own 'getOrRequest' value.
The name needs to be changed in order to make each duplicated group of radio buttons selectable without affecting every other radio button. What is the best way to change these values?
Here is how I'm duplicating the div, in case that is the issue.
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
bookInfo.appendChild(copyDiv);
I then have tried a couple methods of changing the name value. Like this:
bookInfo.copyDiv.getOrRequest_0.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
bookInfo.copyDiv.getOrRequest_1.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
As well as this:
bookInfo.copyDiv.getOrRequest_0.name = 'getOrRequest' + idNumber + '[]';
bookInfo.copyDiv.getOrRequest_1.name = 'getOrRequest' + idNumber + '[]';
getOrRequest_0 and getOrRequest_1 are the ID's of the input values, but I've tried it a few ways now and nothing seems to work. Thanks in advance!
EDIT: MORE INFO
Here is the specific code I'm using:
function addAnotherPost(){
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = 'addListing' + idNumber;
for(var j = 0; j < size; j++){
if(copyDiv.childNodes[j].name === "getOrRequest[]"){
copyDiv.childNodes[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
And it just doesn't seem to work.. The divs are duplicating, but the name value is not changing.
You can try this - http://jsfiddle.net/ZKHF3/
<div id="bookInformation">
<div id="addListing">
<input type="radio" name="addListing0[]" />
<input type="radio" name="addListing0[]" />
</div>
</div>
<button id="button">Add Listing</button>
<script>
document.getElementById("button").addEventListener("click", AddListing, false);
var i = 1;
var bookInfo = document.getElementById('bookInformation');
function AddListing() {
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = "listing" + i;
for ( var j = 0; j < size; j++ ) {
if ( copyDiv.childNodes[j].nodeName.toLowerCase() == 'input' ) {
copyDiv.childNodes[j].name = "addListing" + i + "[]";
}
}
bookInfo.appendChild(copyDiv);
i++;
}
</script>
The trouble is you are looking for child nodes of the div, but the check boxes are not child nodes, they are descendant nodes. The nodes you are looking for are nested within a label. Update your code to look for all descendant inputs using copyDiv.getElementsByTagName("input"):
var idNumber = 0;
function addAnotherPost() {
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
copyDiv.id = 'addListing' + idNumber;
var inputs = copyDiv.getElementsByTagName("input");
for(var j = 0; j < inputs.length; j++){
if(inputs[j].name === "getOrRequest[]"){
inputs[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
http://jsfiddle.net/gilly3/U5nsa/

Categories

Resources