Getting array from text - javascript

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>

Related

How to dynamically add <a> tags given an index of HTML page's string?

I'm making a search function for my website. So far, I've found the string the user searches for in the whole website, and I'm able to print the string and the context of the string. I have achieved this by using $.get on my HTML pages, then stripping the HTML to leave the pure text I want to search in. I then find the index of the string I'm looking for, then use substr to find the context of the input string (a few indexes ahead and behind).
Now, I need to link to the original page when a user clicks on a search result. My research says to use <a> tags, but how do I dynamically insert those into the HTML page with the index I have? And the index I have isn't even the complete page; it's stripped of tags.
These are the relevant parts of my code:
JavaScript:
function getIndicesOf(searchStr, str) { //get the indices of searchStr inside of str
var searchStrLen = searchStr.length;
if (searchStrLen == 0) {
return [];
}
var startIndex = 0, index, indices = [];
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
return indices;
}
function search() {
obj=document.getElementById("searchButton");
obj.onclick = function() {
var searchInput = document.getElementById('searchBox').value;
var allPageContent = ['chap/telem.php', 'chap/nestor.php', 'chap/aeolus.php', 'chap/calypso.php', 'chap/circe.php', 'chap/cyclops.php', 'chap/eumaeus.php', 'chap/hades.php','chap/ithaca.php', 'chap/lestry.php', 'chap/lotus.php', 'chap/nausicaa.php', 'chap/oxen.php', 'chap/penelope.php', 'chap/proteus.php', 'chap/scylla.php', 'chap/sirens.php', 'chap/wrocks.php']; //contains all text
var allText = '';
for (var i = 0; i < allPageContent.length; i++){
$.get(allPageContent[i], function(data){
var div = document.createElement("div");
div.innerHTML = data;
//allText = div.textContent || div.innerText || ""; //gets the text to search in, stripped of html
alltext = data;
allText = allText.replace(/(\r\n\t|\n|\r\t)/gm," ");
console.log(data);
var indices = getIndicesOf(searchInput, allText); //the variable indices is the array that contains the indices of the searched text in the main text
indices.forEach(findContext);
})
}
localStorage.output = '';
function findContext(currentValue, index) {
if (currentValue <= 16) {
searchContext = "..." + allText.substr(currentValue, 100) + "...";
} else {
searchContext = "..." + allText.substr(currentValue-15, 100) + "...";
}
localStorage.output = localStorage.output + searchContext + "<br /><br />";
}
console.log(localStorage.output);
};
};
HTML:
<script>document.getElementById("output").innerHTML = localStorage.output;</script>
It's a bit confusing what you're trying to achieve, considering your HTML, but replying to this
My research says to use <a> tags, but how do I dynamically insert
those into the HTML page with the index I have?
this would do the trick
var output = document.getElementById("output");
var a = document.createElement("a");
var linkText = document.createTextNode("my linked text");
a.appendChild(linkText);
a.href = "http://example.com";
output.appendChild(a);

JavaScript - Adding text box values an storing it in an array

i need some code corrected. So here is the JS:
var $ = function (id) {
return document.getElementById(id);
}
var myTransaction = new Array[];
function processInfo() {
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = myTransaction;
for (var theTotal in myTransaction) {
myTransaction += addTogether[theTotal] + "<br>";
}
}
window.onload = function () {
$("addbutton").onclick = processInfo;
}
and HTML
<section>
<p>Item:
<input type="text" id="item" size="30">
<p>Amount:
<input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p>
<input type="button" id="addbutton" value="Add Item" onClick="processInfo();">
</section>
What i need to do is get the values of the text boxes, and add them together into one variable then have it stored into the array. Then use a for-in loop to concatenate every element in the Array into a one String variable. However, must also stick a tag at the end every value in the String, last thing is place this String in a paragraph at the end of the page.
FIDDLE
If I understand you then look at my edition to your code:
If you not understand something with the code so ask me.
At first you forget to close with ; the function $.
then you create array with bad syntax.
third you call addTogether array that doesn't exist.
this is fixed code that i belive working like you asked.
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
for (var theTotal in myTransaction)
{
myParagraph.innerHTML += myTransaction[theTotal] + "<br>";
}
};
(function () {
$("addbutton").onclick = processInfo;
})();
Edit
Mohamed-Ted suggest:
instead of:
for (var theTotal in myTransaction)
{
myParagraph.innerHTML += myTransaction[theTotal] + "<br>";
}
you can do this:
myParagraph.innerHTML += myTransaction.join("<br>");
see example on:
jsFiddle

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 + '; ';
}

Why is my Javascript not valid?

I have a div with ID 'adpictureholder', to which I dynamically add (or remove) images.
On Form submit I want to get SRC values of all these images within that DIV and put them to the value of one hidden input with ID 'piclinkslisttosubmit'. The thing is that my current Javascript does not function as if there is some syntax typo there, but I don't see where. Can anyone please have a quick look at it?
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes[].length - 1;
var images = document.getElementById('adpictureholder').childNodes[];
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
}
Change childNodes[] to simply childNodes.
You don't need to specify that a variable you're referencing is an array by adding brackets.
Your javascript isn't valid because you keep putting childNodes[] you can solve that by replacing childNodes[] with simply childNodes
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes.length - 1;
var images = document.getElementById('adpictureholder').childNodes;
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
} ​
You shouldn't use [] when reading a property value:
var images = document.getElementById('adpictureholder').childNodes;
You can then get the length from the array, instead of reading the property again:
var endi = images.length - 1;
First off you don't need the [] after childNodes. that causes an error.
You also were forgetting that childNodes includes text nodes and would not work properly, because they did not all contain the src property. I've corrected that in the following example:
function copyonsubmit() {
var str = '';
var textbox = document.getElementById('piclinkslisttosubmit');
var i = 0;
var images = document.getElementById('adpictureholder').childNodes;
var numImages = images.length - 1;
var src = "";
for (i = 0; i < numImages; i++) {
if (images[i].tagName === "IMG") {
str += images[i].src + '|';
}
}
str = str.slice(0, -1); // cut off the final |
textbox.value = str;
}
http://jsfiddle.net/NWArL/2/
Secondly you could write this really simply with jQuery.
var str = "";
$("#apictureholder").children("img").each(function() {
str += $(this).attr("src") + "|";
})
$("#piclinkslisttosubmit").val(str);
Third off make sure to check your console for errors. It was very clear when I ran this code on JSFiddle that it had a problem.
Finally, what exactly are you trying to do?
Change childNodes[] to childNodes and rest looks fine to me,
Read about childNodes
Try,
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes.length - 1;
var images = document.getElementById('adpictureholder').childNodes;
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
}
You said you were using jQuery, but you presented us with vanilla Javascript. I took the liberty of converting your code to jQuery and cleaning it up a bit. The others have already identified your problem, though.
function copyonsubmit() {
var strump1 = '';
var images = $("#adpictureholder")[0].childNodes;
for (var i = 0; i < images.length; i++) {
strump1 += '|' + images[i].src;
}
$('#piclinkslisttosubmit').val(strump1);
}​

Any ideas on what is wrong with this javascript code?

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';

Categories

Resources