Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I seem to be having an issue with my JSON objects, which is unusual because I have one block of code I know works:
function gotoPassage(id) {
for (var i = 0; i < passages.length; i++) {
if (passages[i].id == id) {
if (passages[i].bgImage)
changeBGImage(passages[i].bgImage);
$("#passage").hide();
$("#passage").html(passages[i].content);
$("#passage").fadeIn(1000);
}
}
}
The above code works as expected, so I assumed the same logic and applied it to my other code, which - by the way - does not render correctly. This code currently looks something like this:
function showLoreHistory() {
$("#lore ul").html("");
for (var i = 0; i < foundLore.length; i++) {
var content = "<li><a href='javascript:gotoLore(" + foundLore[i].id ");'>";
for (var j = 0; j < lore.length; j++) {
if (lore[j].id == foundLore[i].id) {
content += lore[j].title + "</a></li>";
$("#lore ul").append(content);
break;
}
}
}
$("#lore").toggle();
}
The structure of lore and foundLore look like this:
var lore = [{
"id": 0,
"title": "The First War",
"image": "Images/The First War.jpg",
"pages": [{
"content": ""
}]
}];
var foundLore = [{
"id": 0
}];
I was thinking of iterating through the keys of each JSON object, but found that it looked ugly, and considering my previous logic for showing passages worked assumed that the same logic would work for my Lore, but it does not seem to.
I would come up with a JSFiddle but unfortunately I rely on too many local resources to get it working properly without sacrificing code, which would defeat the point of me explaining the issue.
EDIT: If I comment out the for loops in the function showLoreHistory, the page will render correctly as expected in the following image.
EDIT 2: What I am trying to do is get the values from the above JSON object and adding the values to HTML, under a div tag namely lore - which is hidden by default.
The Div tag, with its content, looks like this:
<div id="lore">
<h1>Lore</h1>
<ul>
</ul>
</div>
If you have any solutions regarding this, I would strongly appreciate it. Thank you.
this line
var content = "<li><a href='javascript:gotoLore(" + foundLore[i].id ");'>";
is missing a '+' after foundLore[i].id
Also, the toggle is probably not what you want. I think you should hide it at the beginning of the function, then show it at the end like in your other function where you show the image.
If you open developer tools (f12 or ctrl+shift+j) it will show you errors like that.
p.s. it took literally under 2 minutes to make a fiddle for me to find the problem.. Give it a shot next time.
http://jsfiddle.net/8cr9t1zy/2/
You have to hit the button twice because of the toggle() thing I mentioned above.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this function which produces the correct value when run, but I am having a hell of a time displaying the results.
Here is the JS which is calculated onChange in a form I am trying to display the resulting value elsewhere on the form. The alert displays the correct value but my id remains blank.
Thanks in advance for taking a look
function calculate_mtow1() {
togw_n = 0;
togw = $('#togw').val();
if (togw != '' && togw != 0 && togw != 'Nan') {
var togw = togw.replace(",", "");
togw_n = togw;
}
burn_n = 0;
burn = $('#burn').val();
if (burn != '' && burn !=0 && burn != 'Nan') {
var burn = burn.replace(",", "");
burn_n = burn;
}
var mtow1 = parseInt(togw_n) + parseInt(burn_n);
$('#mtow1').val(mtow1);
document.getElementById('mtow1');
alert(mtow1);
}
<td>TOW + Fuel Burn =<span id="mtow1"></span></td>
Your code is getting the element with getElementById but then not doing anything with it. You need to assign the result of getElementById to something, or call methods on it on the same line. If your goal is to put the value of mtow1 into your <span>, try doing this:
// Solution 1
var spanElement = document.getElementById("mtow1");
spanElement.innerHtml = mtow1;
Alternatively, perhaps you were trying to display the value of mtow1 by using this jQuery:
$('#mtow1').val(mtow1);
That doesn't do what you think it does. It changes the "value" attribute of the span to the value of mtow1, but that change isn't visible to the user. It's the same as writing this as your HTML:
<td>TOW + Fuel Burn =<span id="mtow1" value="valueofmtow1"></span></td>
If you want to use jQuery instead of the getElementById method I posted above, you could do this:
// Solution 2
$('#mtow1').html(mtow1);
You don't need to do both. Either solution will work on its own.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a basic Node.js script that creates a JSON array from a few variables and other arrays.However, whenever I call on myJSON.title in my code it does not work at all. It gives undefined. Could anyone please help me?
for (var i = 0; i < route.length; i++) {
var item = {
"title": title[i],
"date": date[i],
"summary": summary[i],
"route": route[i],
"pebbleid": "geoquery-" + timegreeting + route[i]
};
myarray.push(item);
for (var i = 0; i < route.length; i++) {
var item = {
"title": title[i],
"date": date[i],
"summary": summary[i],
"route": route[i],
"pebbleid": "geoquery-" + timegreeting + route[i]
};
myarray.push(item);
}
myJSON = JSON.stringify({delays: myarray});
console.log(myJSON);
}
The reason myJSON.title is undefined is that JSON.stringify returns a string, and strings don't have a title property.
The object represented by the JSON string myJSON has a single property, delays, (because that's what you put in JSON.stringify). The value of that property is an array. Each element of that array is an object that has a title property (and date, summary, etc.). So to get any one title, you first have to retrieve the delays array and then retrieve one of its elements by index, and then retrieve that element's title property.
So for e.g. the 0th element in delays, you would do this:
obj.delays[0].title
I used "obj" because this will not work with myJSON, because like I said, in the code you've shown myJSON is a JSON string, not a JavaScript object, and so doesn't have a delays property.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
[EDIT] I solved the problem using D3, nevermind thanks!
So I have a csv file that looks something like this, and I need to import a local csv file into my client side javascript:
"L.Name", "F.Name", "Gender", "School Type", "Subjects"
"Doe", "John", "M", "University", "Chem I, statistics, English, Anatomy"
"Tan", "Betty", "F", "High School", "Algebra I, chem I, English 101"
"Han", "Anna", "F", "University", "PHY 3, Calc 2, anatomy I, spanish 101"
"Hawk", "Alan", "M", "University", "English 101, chem I"
I eventually need do parse it and output something like:
Chem I: 3 (number of people taking each subject)
Spanish 101: 1
Philosophy 204: 0
But for now, I am stuck on just importing it into javascript.
My current code looks like this:
<!DOCTYPE html>
<html>
<body>
<h1>Title!</h1>
<p>Please enter the subject(s) that you wish to search for:</p>
<input id="numb" type="text"/>
<button onclick="myFunction()">Click me to see! :) </button>
<script>
function myFunction() {
var splitResearchArea = [];
var textInput = document.getElementById('numb').value;
var splitTextInput = textInput.split(",");
for(var i =0; i<splitTextInput.length; i++) {
var spltResearchArea = splitTextInput[i];
splitResearchArea.push(spltResearchArea);
}
}
I've researched and found some helpful links on Stackoverflow like this, this, and this but I'm new to javascript and I don't completely understand it. Should I use Ajax? FileReader? jQuery? What are the benefits of using one over the other? And how would you implement this in code?
But yeah, I'm just confused since I'm very new to javascript, so any help in the right direction would be great. Thank you!!
Here is how to use the readAsBinaryString() from the FileReader API to load a local file.
Basically, just need to listen to change event in <input type="file"> and call the readFile function.
const fileInput = document.getElementById('csv')
const readFile = () => {
const reader = new FileReader()
reader.onload = () => {
document.getElementById('out').innerHTML = reader.result
}
// start reading the file. When it is done, calls the onload event defined above.
reader.readAsBinaryString(fileInput.files[0])
}
fileInput.addEventListener('change', readFile)
<div>
<p>Select local CSV File:</p>
<input id="csv" type="file" accept=".csv">
</div>
<pre id="out"><p>File contents will appear here</p></pre>
jsFiddle
There are as many ways of accomplishing what you want as you could possibly imagine.
If I were doing this, I might start by splitting the input text into lines like so:
var lines = inputText.split('\n');
Then, I would extract the names of the headers from the first line.
You need a function to read the values from each line.
// This assumes no commas in the values names.
function getCsvValuesFromLine(line) {
var values = line[0].split(',');
value = values.map(function(value){
return value.replace(/\"/g, '');
});
return values;
}
var headers = getCsvValuesFromLine(lines[0]);
Next, I would loop over the remaining lines and create an array of objects representing the values in the lines.
lines.shift(); // remove header line from array
var people = lines.map(function(line) {
var person = {};
var lineValues = getCsvValuesFromLine(line);
for (var i = 0; i < lines.length; i += 1) {
person[headers[i]] = lineValues[i];
}
return person;
});
If this all works, you should end up with an array of objects representing the values in each line in your CSV.
The above is a rough outline of what the code might look like. I have not tested it and it certainly is not production ready, but I hope it gives you an idea of how to go about doing what you want.
I've used several built-in Javascript functions. I suggest looking them up on MDN if you're not familiar with them; they are good to know.
Finally, there is an odd quirk in Javascript with its automatic semi-colon insertion (a bad feature of the language, IMO). In order to avoid problems, do not put a new-line before an opening brace.
Always write
XXXX {
....
}
and don't write
XXXX
{
....
}
i use this library from google: https://github.com/evanplaice/jquery-csv/
First - u have to
$.get(ur_csv_file_path);
and then use guide from page
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
can somebody help for my code which is written in python, i want to write it in javascript but im in trouble, i dont know how.
python code
cities={}
for line in open("linnadkaugustega.txt", "r", encoding="UTF-8"):
m=line.strip().split()
abim=[word.split(":") for word in m[1:]]
cities[m[0]]={}
for couple in abim:
cities[m[0]][couple[0]]=int(couple[1])
print(cities);
and i tried in javascript but that doesen't work
function tere(){
console.log("Tere");
$.get('read.txt', function(data) {
cities={};
var lines = (data.trim()).split();
abim=[var word.split(":") for word in m[1:]]
cities[m[0]]={};
for var couple in abim
cities[m[0]][couple[0]]=couple[1];
console.log(cities);
}, 'text');
}
tere();
can somebody help me ?
You have syntax issues translating from python to js. Heres how arrays work...
if you have an array litteral in javascript
var cities = [];
Then we would add to the array by calling push
cities.push('Portland');
...
cities.push('New York');
we can then iterate over the array by calling forEach on the array object.
cities.forEach(function (city, index){
//do work on each city
console.log(city);
});
// Portland
// New York
A few things:
.split() in JS does something different than split in python when no separator is given. To split a line into words, you'll need to split on whitespaces explicitly
you're missing the for loop over the lines of the file. Python uses the iterator syntax for reading from the file, in JavaScript an ajax request loads the whole file and you'll need to split it in lines yourself.
JavaScript does not have that m[1:] syntax, you'll need to use the .slice() method instead
JavaScript does not have array/list comprehensions. You will need to use an explicit loop, or the map method of arrays
your loop syntax is too pythonic. In JavaScript, for loops need parenthesis and an index variable.
So this should do (supposed you have the jQuery library loaded and it finds the file):
$.get('read.txt', function(data) {
var cities = {};
var lines = data.split("\n");
for (var i=0; i<lines.length; i++) {
var line = lines[i];
var m = line.trim().split(/\s+/);
var abim = m.slice(1).map(function(word) {
return word.split(":");
});
var obj = cities[m[0]] = {};
for (var j=0; j<abim.length; j++) {
var couple = abim[j];
obj[couple[0]] = couple[1];
}
}
console.log(cities);
}, 'text');
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So the thing goes as following: I'm a begginer programmer (so far i know HTML, CSS some JavaScript and some C++) and we have a school project to create a chessboard with figures on them but I want to go a step further and be able to move the figures.
So far I've used the prompt function to get the coordinates and move them around but that feels far too much stone-agish. Now what I wish to accomplish is to be able to click on a , copy its content into a variable and upon clicking on another replace its content with the one stored in the variable. (I'll deal with the rules later..)
Each has its unique id and I have used element.firstChild.nodeValue to acquire the content.. Any suggestions on how to do this in JavaScript without using jQuery (if it can't be done in JavaScript then by all means do it in some other language.. it's about time I start learning them anyway.. :P)
If each <td> has a unique id, what about:
var lastStoredValue = "", lastClicked = ""; // = "" is important in that case
var t1 = document.getElementById("t1"); // td with id="t1"
var t2 = document.getElementById("t2"); // td with id="t2"
t1.onclick = function() {
if (lastClicked !== "t1" && lastStoredValue.trim())
t1.innerHTML = lastStoredValue; // replace its content with the one stored in the variable
if (!lastStoredValue.match(new RegExp(t1.innerHTML)))
lastStoredValue= t1.innerHTML; // copy its content into a variable
lastClicked = "t1";
}
t2.onclick = function() {
if (lastClicked !== "t2" && lastStoredValue.trim())
t2.innerHTML = lastStoredValue; // replace its content with the one stored in the variable
if (!lastStoredValue.match(new RegExp(t2.innerHTML)))
lastStoredValue= t2.innerHTML; // copy its content into a variable
lastClicked = "t2";
}
This gets what is stored into one td and puts it into a variable; then stores what is in the variable into another td when click on that td.