How to add the value of a variable to my HTML? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have 2 separate instances in which I show Data from JavaScript in a heading on my page:
Html:
<h2 id='Fetch_Header' style="color:white; font-family: arial;">
The last time you fetched your games was:<span class="last_fetch" style="font-weight: bold;"></span>
</h2>
jQuery:
$.get('php/FetchGames/LastFetch.php', function (data) {
if (data == "Never") {
var lastdate = data;
$('.last_fetch').html(" " + lastdate);
}
more jQuery:
$.get('php/FetchGames/GetMatchCount.php', function (data) {
MatchCountJson = data;
MatchCountJson_Parsed = JSON.parse(MatchCountJson);
MatchCount = MatchCountJson_Parsed.Int;
//the above JSON is {"Int":72}
});
$('#Fetch_Header').html('Time to apply your MMR, follow the instructions below. Matches left to apply: ' + MatchCount);
However only the former works (The lastdate one).
First Output:
date (as expected)
Second Output:
"Time to apply your MMR, follow the instructions below. Matches left
to apply: undefined"
Both of the variables are not null/undefined, since if I use Console.log, then the lastdate is a date, and the Matchcount is an integer (for example 32).

Matchcount is outside of the scope of your code when you try and use it.
.get() is an asynchronous call, meaning it is not guaranteed to be complete when the next instruction is executed. If you want to use anything based on data, it needs to happen within the scope of the callback function in the get() call.
$.get('php/FetchGames/GetMatchCount.php', function(data){
MatchCountJson = data;
MatchCountJson_Parsed = JSON.parse(MatchCountJson);
MatchCount = MatchCountJson_Parsed.Int;
// Call must be inside of "get()" callback
$('#Fetch_Header').html('Time to apply your MMR, follow the instructions below. Matches left to apply: '+MatchCount);
});

You can only use your MatchCount variable in the result of the get method.
Try this
$.get('php/FetchGames/GetMatchCount.php', function(data){
MatchCountJson = data;
MatchCountJson_Parsed = JSON.parse(MatchCountJson);
MatchCount = MatchCountJson_Parsed.Int;
//the above JSON is {"Int":72}
$('#Fetch_Header').html('Time to apply your MMR, follow the instructions below. Matches left to apply: '+MatchCount);
});

The issue is the scope of the data passed back from the server so your second html insert cannot access MatchCount. Change your code to this:
$.get('php/FetchGames/GetMatchCount.php', function(data){
MatchCountJson = data;
MatchCountJson_Parsed = JSON.parse(MatchCountJson);
MatchCount = MatchCountJson_Parsed.Int;
//the above JSON is {"Int":72}
$('#Fetch_Header').html('Time to apply your MMR, follow the instructions below. Matches left to apply: '+MatchCount);
});

Related

how can i make my function reusable whilst using the (e) parameter?

const days = document.querySelector('#days');
const hours = document.querySelector('#hours');
const minutes = document.querySelector('#minutes');
document.querySelector('#years').addEventListener('input', function (e) {
let years = e.target.value;
days.lastElementChild.innerHTML = years * 365;
hours.lastElementChild.innerHTML = years * 8760;
minutes.lastElementChild.innerHTML = years * 525600;
});
I really need help with this one. When using the e parameter i can target the value from when the event is triggered using this code. I get that i can call the parameter anything and use target to access all the juicy information about the event in the console. What i do nott understand is , why cant i pass arguments with the e to make my function reusable. I want to pass my variables via arguments and store placeholders as parameters and work against them. Instead if I store (e) as a parameter, unless i am missing something , I am forced to reference my variables inside my function because I cannot seem to pass other arguments with (e) . Is there a way i can e.target.value and still pass arguments to my function? This one has really got me stuck , thanks
One method is to record the id attribute values for output parent elements as a data attribute on the input element used to enter a year. Another method could involve setting up a table of parent elements using the id of the input as key.
A third option is to add the event listener (which is passed an event object as argument) inside a closure: i.e. inside an outer, reusable function which is called with all necessary argument values to add an event listener to a specific elements and handle events that are raised.
Here's an example of the first approach:
"use strict";
function showDHM(event) {
let years = event.target.value;
event.target.dataset.for.trim().split(/\s*,\s*/)
.map( id => document.getElementById( id))
.forEach( (element, index) => {
const multiplicand = [ 365, 8760, 525600];
element.lastElementChild.innerHTML = years * multiplicand[index];
});
}
const year1 = document.querySelector('#year1')
year1.dataset.for = "days1, hours1, mins1";
year1.addEventListener('input', showDHM);
<label> Year: <input type="number" id="year1"></lable>
<p>
<span id="days1"><span>days</span></span>,
<span id="hours1"><span>hours</span></span>,
<span id="mins1"><span>mins</span></span>
Note the code is for demonstration only: adjustment for leap years not included!
The next snippet demonstrates the closure option. The conversion process used to modify the posted code was largely mechanistic: replace hard-coded values with argument names and include the modified code in an outer function.
"use strict";
function handleYears( yearsSel, daysSel, hoursSel, minutesSel) {
const days = document.querySelector(daysSel);
const hours = document.querySelector(hoursSel);
const minutes = document.querySelector( minutesSel);
document.querySelector(yearsSel).addEventListener('input', function (e) {
let years = e.target.value;
days.lastElementChild.innerHTML = years * 365;
hours.lastElementChild.innerHTML = years * 8760;
minutes.lastElementChild.innerHTML = years * 525600;
});
}
handleYears("#year1", "#days1", "#hours1", "#mins1");
<label> Year: <input type="number" id="year1"></lable>
<p>
<span id="days1"><span>days</span></span>,
<span id="hours1"><span>hours</span></span>,
<span id="mins1"><span>mins</span></span>

Replace particular file content in nodejs

I want to replace a particular line using javascript with new content.
This is the file content,
SERVER=1055#localhost
GROUP_SERVERS=2325#localhost
LINE_IAM_INTERESTED=KTYUIERVW:2800
FILE_PATH="C:\Program Files\somefile\Shared Files\"
In this line, LINE_IAM_INTERESTED=KTYUIERVW:2800 .I want to replace KTYUIERVW with KJHTERDY and 2800 with 78945
I have shown what I tried using fs appendfilesync
fs.appendFileSync('file_name').toString().split('\n').forEach(function(line){
app.console.log("called append");
var sEntry = line.split("=");
if (sEntry.length == 2) {
if (sEntry[0] == "LINE_IAM_INTERESTED") {
app.console.log("found one!!!!");
}
}
});
you can try READ -> REPLACE -> WRITE flow:
fs.writeFileSync('file_name', fs.readFileSync('file_name').replace('KTYUIERVW:2800', 'KJHTERDY:78945'))
appendFile and appendFileSync are used for adding to the end of the file. Although you can do it as a one liner as shown in the other answer, I've kept the structure of your code the same. Here you want to read the data, modify it then re-write it. Using the block of code you have, you can modify it to use readFileSync and writeFileSync.
let newData = fs.readFileSync('file_name', 'utf-8').split('\n').map(line => {
let sEntry = line.split('=')
if (sEntry.length == 2) {
if (sEntry[0] == "LINE_IAM_INTERESTED") {
console.log("found one!!!!");
return sEntry[0] + '=' + 'KJHTERDY:78945'
}
}
return line
}).join('\n')
fs.writeFileSync('file_name', newData)
I've swapped the forEach for map which lets us change the array data by returning the desired value. The new array is then joined back together and written back to the file.

I'm trying to use jquery to create a div containing columns but I can't get my array to format correctly

I have an array that contains dates. and for some reason I can't get it to show on my screen I've been debugging for a few days now and I've tracked it down to a single line, but the line has worked before and I can't figure out what the issue might be.
The array looks like this:
var selectItems =
[ "05-26-2017", "06-02-2017", "06-09-2017",
"06-16-2017", "06-23-2017", "06-30-2017", "07-07-2017", "07-14-2017",
"07-21-2017", "07-28-2017"...];
It's passed as an argument from another function, but that's how it's showing in console.log().
I might be going about this the wrong way, maybe even a lot further around then I need to but this is what I've come up with:
1. function setTHead(selectItems) {
2 var formatString;
3. for (var x = 0; x < 12; x++) {
4. formatString = selectItems[x].replace(/[^0-9/-]/g, "").toString();
5. console.log(selectItems);
6. $('#datTab').append("<div id='col" + x + "' class='column'>'" + formatString + "'</div>");
7. }
8. }
the array up top is what's showing from the console.log 5 lines down.
the sixth line is what is seeming to give me issues. Nothing is put on the page at all.
I'm getting a console error saying:
jQuery.Deferred exception: selectItems is undefined setTHead#http://localhost/mySite/script.js:136:9
startUp2#http://localhost/mySite/script.js:146:5
#http://localhost/mySite/table.php:19:9
mightThrow#http://localhost/mySite/lib/jquery.js:3586:52
resolve/</process<#http://localhost/mySite/lib/jquery.js:3654:49
setTimeout handler*resolve/<#http://localhost/mySite/lib/jquery.js:3692:37
fire#http://localhost/mySite/lib/jquery.js:3320:30
fireWith#http://localhost/mySite/lib/jquery.js:3450:29
fire#http://localhost/mySite/lib/jquery.js:3458:21
fire#http://localhost/mySite/lib/jquery.js:3320:30
fireWith#http://localhost/mySite/lib/jquery.js:3450:29
ready#http://localhost/mySite/lib/jquery.js:3923:13
completed#http://localhost/mySite/lib/jquery.js:3933:9
EventListener.handleEvent*#http://localhost/mySite/lib/jquery.js:3949:9
#http://localhost/mySite/lib/jquery.js:39:9
#http://localhost/mySite/lib/jquery.js:17:3
undefined
followed by:
TypeError: selectItems is undefined
and thats pointing to line 6.
if anyone has any advice I would be very much appreciative. Thank you in advance.
EDIT: A little more code:
function startTblView(defSel) {
if (defSel === true) {
setCookie('defSel', true, 7);
} else{
setCookie('defSel', false, 7);
}
saveSelected();
window.open('table.php', '_self');
defSel = getCookie('defSel');
if (defSel) {
selectItems = getDefDates();
}else {
selectItems = reGetSelected();
}
setTHead(selectItems);
}
defSel, is a boolean passed from my last page stating whether I'm doing a default view or a custom view, the custom view is passed from saveSelected();
saveSelected is a function for just saving the selected global value as a cookie so I can pull it out on the next page.
getDefDates pulls the default values for the array
reGetSelected, gets the selected array from the cookie.
I apologize for wonky naming conventions. I'm the only one working on this site and I'm just making sure the names don't overlap.
You can do this :
HTML code
<div id="datTab"></div>
JS code
var selectItems =
[ "05-26-2017", "06-02-2017", "06-09-2017",
"06-16-2017", "06-23-2017", "06-30-2017", "07-07-2017", "07-14-2017",
"07-21-2017", "07-28-2017"];
function setTHead(selectItems) {
var formatString;
$.each( selectItems, function( index, value ){
formatString = value.replace(/[^0-9/-]/g, "").toString();
$('#datTab').append("<div id='col" + index + "' class='column'>'" + value + "'</div>");
});
};
You can use $.each, its better than 'for' with javascript.
The .each() method is designed to make DOM looping constructs concise
and less error-prone. When called it iterates over the DOM elements
that are part of the jQuery object. Each time the callback runs, it is
passed the current loop iteration, beginning from 0. More importantly,
the callback is fired in the context of the current DOM element, so
the keyword this refers to the element.
I did a JsFiddle
Here.

How is the Argument value set - Javascript

I am new to javascript.
I am trying to understand how the value is set to 'USD' for 'outCurr' argument in the following code, am I missing anything. I understood the rest of the code but could not figure this out.
The example is taken from https://docs.angularjs.org/guide/concepts#model
angular.module('invoice1', [])
.controller('InvoiceController', function()
{
this.qty = 1;
this.cost = 2;
this.inCurr = 'EUR';
this.currencies = ['USD', 'EUR', 'CNY'];
this.usdToForeignRates = { USD: 1, EUR: 0.74, CNY: 6.09 };
this.total = function total(outCurr)
{
return this.convertCurrency(this.qty * this.cost, this.inCurr, outCurr);
};
this.convertCurrency = function convertCurrency(amount, inCurr, outCurr)
{
return amount * this.usdToForeignRates[outCurr] / this.usdToForeignRates[inCurr];
};
this.pay = function pay() {
window.alert("Thanks!");
};
});
What I understand is that both function take 'outCurr' as argument/parameter but I cant see any value assigned to it. Please let me know if I have missed anything.
In the index.html file, there is an ng-repeat that loops through the current currencies (['USD', 'EUR', 'CNY'] array and calls total(c) function and pass each currency.
<b>Total:</b>
<span ng-repeat="c in invoice.currencies">
{{invoice.total(c) | currency:c}}
</span>
So, you need to look at the html file too, as with AngularJS binding and expressions happens in the HTML file.
Hope that helps.
The variable "outCurr" is assigned automatically once the function is called. In the code snippet you see here, the function convertCurr is never called in the Javascript. The special thing about AngularJS is that it enables these functions to be called in the HTML itself. You'll notice that, as explained by Omar, in the snippet below, it passes in the outCurr for each currency in the "currencies" array, thus displaying the resulting value in every currency.
<span ng-repeat="c in invoice.currencies">
{{invoice.total(c) | currency:c}}
</span>

Use of different object properties for same function

In the avatar generator I'm working on I have several button events that do the same thing but with different body parts. I don't want to have different functions doing the same thing, so I want to use one function for all body parts.
Line 14 below uses the object propery 'AvGen.eyes.currEyesNr', but instead I want to use the one for the clicked button. What can I put in as an argument and how can I use the parameter in the function to be able to use the correct object parameter?
1. prevBodyBtn.on('click', function(){
2. if (AvGen.theBody.currBodyNr > 0) {
3. changePart(-1);
4. }
5. });
6.
7. prevEyesBtn.on('click', function(){
8. if (AvGen.eyes.currEyesNr > 0) {
9. changePart(-1);
10. }
11. });
12.
13. function changePart(direction) {
14. AvGen.eyes.currEyesNr += direction; // <-- this is now always 'AvGen.eyes.currEyesNr' but should be dynamic
15.
16. var body = AvGen.theBody.bodies[AvGen.theBody.currBodyNr],
17. eyes = AvGen.eyes.eyes[AvGen.eyes.currEyesNr],
18. nose = AvGen.nose.noses[AvGen.nose.currNoseNr];
19. mouth = AvGen.mouth.mouths[AvGen.mouth.currMouthNr];
20.
21. AvGen.addSVG(body, eyes, nose, mouth);
22. }
Change names of the properties indicating current index values from currBodyNr, currEyesNr etc to currNr.
Then you can address required property of AvGen by name:
function changePart(direction, bodyPartName) {
var part = AvGen[bodyPartName];
part.currNr += direction;
...
and call it:
changePart(-1, "eyes");
or
changePart(-1, "theBody");
Another way to do it is to simply pass the body part that needs to change as a second parameter:
function changePart(direction, bodyPart) {
bodyPart.currNr += direction;
and call it:
changePart(-1, AvGen.eyes);
You can pass an argument to the 'click' event callback, and check which item was clicked.
Than use it to pass whatever you want to the 'changePart' function. ( you can read some data you have in the clicked element for example to pass them to your function )
prevEyesBtn.on('click', function(e){
e.currentTarget; // this is the element that was clicked for example
if (AvGen.eyes.currEyesNr > 0) {
changePart(-1);
}
});

Categories

Resources