I am writing a function that when called prints out the same image 7 times. When calling the function I am passing it a 0 in the parameters. Here is the function:
function showCards(numcards) {
while (numcards < 7) {
var data = ""
data += "<td><img src='http://www.biogow.com/images/cards/gbCard52.gif' NAME='card0' ></td>"
numcards = numcards + 1
}
return (data)
}
However, when this function is called, it only prints one image. How can I get it to print all seven? Any ideas? Thanks!
Put the var data = "" outside of the loop. As is, it is reset on every iteration.
function showCards(numcards)
{
var data = ""
while (numcards < 7)
{
data += "<td><img src='http://www.biogow.com/images/cards/gbCard52.gif' NAME='card0' ></td>"
numcards = numcards + 1
}
return (data)
}
Related
I'm trying to accomplish three functions, where one gets two values from HTML-elements, one counts exponent of these values and one console.logs what the values used were and the result.
What way would function noudaArvo be able to pass both variables to other functions? I'm trying not to change other two functions.
function laskuFunktio() { //does the printing
var luku = noudaArvo("luku");
var eksp = noudaArvo("eksponentti");
console.log("Luku " + luku + " potenssiin " + eksp + " on:");
console.log(laskePotenssi(luku, eksp));
}
function noudaArvo() { //gets the values, but can't figure how to pass them out
let luku = document.getElementById("luku").value;
let eksponentti = document.getElementById("eksponentti").value;
}
function laskePotenssi() { //counts the exponent
var luku = noudaArvo("luku");
var eksponentti = noudaArvo("eksponentti");
return Math.pow(luku, eksponentti);
}
function laskuFunktio() { //does the printing
var luku = noudaArvo("luku");
var eksp = noudaArvo("eksponentti");
console.log("Luku " + luku + " potenssiin " + eksp + " on:");
console.log(laskePotenssi(luku, eksp));
}
function noudaArvo(item) { //gets the values, but can't figure how to pass them out
return document.getElementById(item).value;
}
function laskePotenssi(luku, eksp) { //counts the exponent
return Math.pow(luku, eksp);
}
If I understand what your saying correctly this may be a solution to your problem
U don't return from noudaArvo function anything
change the function to
function noudaArvo(elId) { //gets the values, but can't figure how to pass them out
return document.getElementById(elId).value;
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I'm new to working with AJAX, but I've been researching it for the past two hours to help in my scenario. I haven't made any progress. :(
Regardless, my issue is that the subPages array is out of scope when I'm outside $.get(...). I've tried using when() and done() for my code, but just can't get it right still.
I think the problem lies within the iterations going through a for loop since I have pages[i] in multiple sections of my code being used. That's why I can't use when() and done() when needed.
Here's what I have:
var subPages = [];
var containsSub = '/sites/Pages/';
var tempString = '';
// iterate through the pages array in reverse
for(var i = pages.length - 1; i >= 0; i--){
// grab all <a> within response text
var getLinks = $.get(baseURL + pages[i]).then(function(responseData){
var $response = $(responseData);
var $links = $response.find('a');
// push each valid link into subPages array
$links.each(function(index, $link){
if(this.href.indexOf(containsSub) > -1){
subPages.push(this.href);
}
});
// subPages array is loaded with the correct values
console.log("subPages inside get: " + subPages);
});
// empty here
console.log("subPages outstide all: " + subPages);
Edit: With the addition of the then chain and code, I'm having an undefined for subPages[i]
var subPages = [];
var containsSub = '/sites/Pages/';
var tempString = '';
// iterate through the pages array in reverse
for(var i = pages.length - 1; i >= 0; i--){
// grab all <a> within response text
var getLinks = $.get(baseURL + pages[i]).then(function(responseData){
var $response = $(responseData);
var $links = $response.find('a');
// push each valid link into subPages array
$links.each(function(index, $link){
if(this.href.indexOf(containsSub) > -1){
subPages.push(this.href);
//console.log("<a href='"+ this.href + "'>" + this.href + "</a>" + " <br>");
}
});
console.log("subPages inside get: " + subPages);
})
.then(function(){
console.log("subPages outstide all: " + subPages);
// print bold for current main page
tempString += "<strong><a href='"+ baseURL + pages[i] + "'>" + pages[i].substr(27,pages[i].length) + "</a><strong>" + " <br>";
for(var i = 0; i < subPages.length - 1; i++){
console.log("<a href='"+ subPages[i] + "'>" + subPages[i] + "</a>" + " <br>");
}
subPages = [];
pages.splice(i, 1);
})
}
11/25 Edit: I fixed the issue below with my answer by removing some complications and decided that an AJAX request was more in logic.
var subPages = [];
var containsSub = '/sites/it/InfoProtect/Pages/';
var tempString = '';
// iterate through the pages array in reverse
for(var i = pages.length - 1; i >= 0; i--){
// grab all <a> within response text
var getLinks = $.ajax({
url: baseURL + pages[i],
async: false,
success: function(responseData){
var $response = $(responseData);
var $links = $response.find('a');
// push each valid link into subPages array
$links.each(function(index, $link){
if(this.href.indexOf(containsSub) > -1){
subPages.push(this.href);
}
});
}
})
Your for loop immediately executes all iterations of the loop. The subPages array is populated after the last line of console.log has run.
$.get is asynchronous, so after calling it, the code inside .then is not immediately called. So, it continues to the next iteration of your loop, finally exits, and shows an empty subpages array, because your data hasn't returned yet.
Here's a quick idea of how to wait for your ajax calls, prior to logging the array (untested):
var ajaxCalls = [];
// iterate through the pages array in reverse
for(var i = pages.length - 1; i >= 0; i--){
// grab all <a> within response text
var getLinks = $.get(baseURL + pages[i]).then(function(responseData){
var $response = $(responseData);
var $links = $response.find('a');
// push each valid link into subPages array
$links.each(function(index, $link){
if(this.href.indexOf(containsSub) > -1){
subPages.push(this.href);
}
});
// subPages array is loaded with the correct values
console.log("subPages inside get: " + subPages);
});
ajaxCalls.push(getLinks);
}
$.when.apply(null, ajaxCalls).then(function() {
// not empty here
console.log("subPages outstide all: " + subPages);
});
issue is that the subPages array is out of scope when I'm outside
$.get(...)
$.get() returns an asynchronous response . Try chaining .then() to $.get() to maintain same scope as initial .then()
var getLinks = $.get(baseURL + pages[i]).then(function(responseData){
})
.then(function() {
console.log("subPages outstide all: " + subPages);
})
Try creating an IIFE within for loop to pass i
e.g.,
var pages = ["a", "b", "c"];
for(var i = pages.length -1; i >= 0; i--) {
(function(j) {
var dfd = $.Deferred(function(d) {
setTimeout(function() {
d.resolve(j)
}, Math.random() * 1000)
}).promise()
.then(function(n) {
console.log("first", n, pages[n]);
return n
}).then(function(res) {
console.log("second", res, pages[res])
})
}(i))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
So i am reading a local json file that consist of {[Object,Object,Object.....]}
I am using the
$.getJSON('products.json', function (pdata) {
for (var i = 0; i < pdata.data.length; i++) {
AppendtoDom(pdata.data[i]);
}
The above code reads the json objects and appends to the DOM, but i want to initially load only 100 objects at a time and on scroll keep appending.
Say there are around 1200 objects. How do i go about this?
My implementaion so far
$(function(){
loadData();
});
function loadData(){
$.getJSON('products.json', function (pdata) {
var i = 0;
function addtoDom(num){
var limit = Math.min(i + num, pdata.data.length);
for(; i < limit; i++){
getInformation(pdata.data[i]);
}
}
addtoDom(100);
$('.content').jscroll({
callback: addtoDom(100)
});
});
}
function getInformation(obj){
var content = "";
for (var i = 0; i < 4; i++) {
content += '<li>';
content += "<img src='" + obj.imageUrl + "' style='width:200px;height:200px'/>";
content += '<div class="productName">' + obj.fullName + "</div>";
content += '<div class="price">Price: ' + obj.price + "</div>";
content += '</li>';
}
$("<ul class= 'view'>" + content + "</ul>").appendTo('.content');
}
Similar question i asked in How would i implement an infinite scroll in my DOM
You can put all the objects you get back from the Ajax call into a persistent variable, add the first 100 to the DOM, keep a counter of how many you've added so far and then upon scrolling to a certain point, add another 100, add another 100 and so on.
$.getJSON('products.json', function (pdata) {
var i = 0;
function addMore(num) {
var limit = Math.min(i + num, pdata.data.length);
for (; i < limit; i++) {
AppendtoDom(pdata.data[i]);
}
}
// add the first 100
addMore(100);
// then set up whatever scroll detection you want here and
// when you decide that it has scrolled enough to add some more
// you just call addMore(100) again
});
In your specific implementation of the above idea, you have an implementation mistake. You have to pass a function reference for the callback so change this:
$('.content').jscroll({
callback: addtoDom(100)
});
to this:
$('.content').jscroll({
callback: function() {addtoDom(100);}
});
Assign your JSON to a variable and dynamically render them as needed.
var json;
$.getJSON('products.json', function (pdata) {
JSON = pdata;
};
// Scheduling logic
AppendtoDom(json[i]);
HELP! I am having an issue w/ one of my Javascript functions that has an inner Javascript function driven by an 'onreadystatechange'.
So all I am looking to do in my main JS code is figure out the value of jsonWR.SURG.EXIST_IND when this function runs. When the INNERretval alert runs, the value is correctly outputting to 1....this is what I expect. Then right before I return the value at the end of the main surgeryScheduled() function, ENDretval is saying the value is now 0.
I am sure I am missing something fundamental here, so can someone help me.
Plus, when surgeryScheduled() function is being called, I set a variable to the return value:
var q = 0;
q=surgeryScheduled(<someID>);
alert("q:"+q);
The above alert returns 1 when I would expect it to return 0 since ENDretval above was 0. What am I missing here??
function surgeryScheduled(srgnID){
var srgnPrsnlID = srgnID;
var sdt = document.getElementById('sdt').value;
var sdtc = sdt.toUpperCase();
var edt = document.getElementById('edt').value;
var edtc = edt.toUpperCase();
var paramString;
paramString =""
paramString += '^MINE^,'
+ srgnPrsnlID
+ ',^'
+ sdtc
+ '^,^'
+ edtc
+ '^'
var WRInfo = new XMLCclRequest();
//; Call the ccl progam and send the parameter string
WRInfo.open("GET", "CH_MP_HAVE_SURGERY_SCHED");
WRInfo.send(paramString);
//; Get the response
WRInfo.onreadystatechange = function () {
if (WRInfo.readyState == 4 && WRInfo.status == 200) {
var jsonWRResp = WRInfo.responseText;
if (jsonWRResp != undefined && jsonWRResp.length !=0) {
jsonWR = eval('(' + jsonWRResp + ')');
}
//; Make sure everything checks out, then return bool
if (jsonWR){
retval = jsonWR.SURG.EXIST_IND;
alert("INNERretval:"+retval);
}//;jsonWR
}//;WRInfo.readyState == 4 && WRInfo.status == 200
}//;WRInfo.onreadystatechange
alert("ENDRetval:"+retval);
return retval;
}
I am trying to dynamically make divs that are clickable. I have inserted a test function. The test function runs even though the div has not been clicked.
function displayResults(responseTxt)
{
var results = document.getElementById("results");
jsonObj = eval ("(" + responseTxt + ")");
var length = jsonObj.response.artists.length;
results.innerHTML = "Please click on an artist for more details: "
for ( var i = 0; i < length; i++)
{
var entry = document.createElement("div");
var field = document.createElement("fieldset");
entry.id = i;
entry.innerHTML = i + 1 + ". " + jsonObj.response.artists[i].name;
field.appendChild(entry);
results.appendChild(field);
//entry.addEventListener("click", idSearch(jsonObj.response.artists[i].id), false);
entry.addEventListener("click", test(), false);
}
} // end function displayResults
function test()
{
document.getElementById("results").innerHTML = "tested";
}
You are calling the test() function and passing its return value to .addEventListener(). Remove the parentheses:
entry.addEventListener("click", test, false);
So that you pass the function itself to .addEventListener().
That answers the question as asked, but to anticipate your next problem, for the line you've got commented out you'd do this:
entry.addEventListener("click",
function() {
idSearch(jsonObj.response.artists[i].id);
}, false);
That is, create an anonymous function to pass to .addEventListener() where the anonymous function knows how to call your idSearch() function with parameters. Except that won't work because when the event is actually triggered i will have the value from the end of the loop. You need to add an extra function/closure so that the individual values of i are accessible:
for ( var i = 0; i < length; i++)
{
var entry = document.createElement("div");
var field = document.createElement("fieldset");
entry.id = i;
entry.innerHTML = i + 1 + ". " + jsonObj.response.artists[i].name;
field.appendChild(entry);
results.appendChild(field);
// add immediately-invoked anonymous function here:
(function(i) {
entry.addEventListener("click",
function() {
idSearch(jsonObj.response.artists[i].id);
}, false);
})(i);
}
That way the i in jsonObj.response.artists[i].id is actually going to be the parameter i from the anonymous function which is the individual value of i from the loop at the time each iteration ran.