I'm trying to create a page that allows for the multiple upload of images, this requires different name attributes. To achieve this, I'm using JS to add one the variable i giving a number.
The below code returns NaN, I'm not too sure why?
$('document').ready(function() {
var i = 1;
$('#new-dialogue').click(function() {
var i = i + 1;
$('.create-upload').append('<div class="upload"><input type="file" name="image' + i + '"/></div>');
});
});
Remove the second var.
What your current code is saying, is what when new-dialogue is clicked, it should create a variable called i and set it to i+1... but because i hasn't been defined yet in this scope you are doing undefined + 1, which is NaN.
Removing the second var will cause the click function to get the i variable from the containing scope, which is what you want it to do. You can then just have i++ to increment it as needed.
That said, you could just make your life easier by using:
<input type="file" name="image[]" />
Because on the server side, you will then have an array of uploaded files ;)
Instead of
var i = i + 1;
Just do
i++;
You need to increment already declared variable, not re-declare it again.
When you redeclared i local to the callback, your function got its own local copy of i that had yet to receive a value. So var i = i + 1; is basically var i = undefined + 1;, which evaluates to NaN.
Get rid of the var to fix this.
Related
I came over a JS somewhere in google documentation:
function doGet() {
var feed = UrlFetchApp.fetch('http://xkcd.com/rss.xml').getContentText();
feed = feed.replace(
/(<img.*?alt="(.*?)".*?>)/g,
'$1' + new Array(10).join('<br />') + '$2');
return ContentService.createTextOutput(feed)
.setMimeType(ContentService.MimeType.RSS);
}
First line declares the function. Second line declares the variable "feed". BUT thrid line is equating the "feed" with something "happening with feed".
How is it possible? It's something like declaring, 2 = 2 + 1.
Note: I just know the basics of JS.
At the first line you assign the text that is returned from a call to an API to the variable called feed.
At the second line you assign at the same variable, feed the result of applying a replace in the result you have taken above.
It's just this, nothing more or less.
By the way the operator = is the assignment operator. It is not related with the equality operator.
For further info about the latter, please have a look here.
You can set a variable to a manipulated value of the variable. A simpler example than what you posted would be like this:
var myNumber = 20;
myNumber = myNumber + 20; //returns 40
Today while working with some JS I had a bug in my code. I was able to resolve it but I don't really understand why the change I made works. All I can guess is that it comes down to either closure or variable scope.
I was trying to build up a nested hash of arrays like so:
var maxNumberOfPairs = 2;
var container = {};
var pairsHash = {};
$.each(["nurse", "doctor", "janitor", "chef", "surgeon"], function(index, role) {
for(var i = 0; i < maxNumberOfPairs; i++){
var pairIdSubString = "attribute_" + i + "_" + role;
pairsHash["attribute_" + i] = [pairIdSubString + "_night", pairIdSubString + "_day"];
}
container [role] = pairsHash;
});
If you run this you get a nice nested output inside container but when you look at each array in the hash you get a weird behaviour with the string produced.
Each one has the last role in each string like so:
"attribute_0_surgeon_night"
If you log out the variable pairIdSubString it correctly has the role in the string, but as soon as this is added to pairHash it just uses the last element in the $.each array.
I was able to fix it by moving pairsHash inside the $.each but outside the for loop.
Can anyone explain to my why the output was different after moving it inside the each?
Thanks
It actually has to do with reference vs value. When its outside the each you are operating on the same object over and over so every time you set it to the container you are just setting a reference to the same object that is constantly changing. So every reference in container after the loop is the last state of the pairsHash because they all point to the same object.
When you put the pairsHash in the each it is reinitialized every time so they all point to different memory addresses. Not the same one since a new one is created every loop.
To further clarify all objects are just references to a memory address In JavaScript so in order to get new one you need to initialize or to pass by value to a function clone it.
How do I increment an integer inside a variable, every time that variable is called? Javascript.
var a=0;
var t=loadXMLDoc("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist="+x[a].getElementsByTagName("name")[0].childNodes[0].nodeValue+"&api_key=83e386b0ba08735e3dee9b118478e56d&lang=en").getElementsByTagName("bio");
for (i=0;i<20;i++)
{
document.write("<div><button type='button' onclick='document.getElementById("+i+").innerHTML=t[0].getElementsByTagName(\"summary\")[0].childNodes[1].nodeValue;'>Open Bio</button></div>");
}
I'm not sure how I would go about incrementing variable a. I need it to increase by 1 every time variable t is called in the for loop.
When I put all of the code in the for loop I get [object node list] returned so this method is not desired.
If I understood your question correctly, you could define your own getters and setters for the property.
var o = {}
o.__defineSetter__('property', function(value) { this._counter = 0; this._holder = value; })
o.__defineGetter__('property', function() { console.log(this._counter++); return this._holder; })
The counter would be reset every time o.property is assigned a value
o.property = 'Some value'
and then increase every time the property is accessed.
So,
console.log(o.property)
would print
0
Some value
to the console. And if you do it again, it would print
1
Some value
After your edit I think I can see your problem now. You will need to put the loadXMLDoc statement in the loop (since you want to load 20 different XML files), but you can't assign the result of every call to the same variable t - as once the button is clicked, the handler will evaluate t and get only the last value.
Instead, use an array:
var bios = []; // empty array
for (var i=0; i<20; i++) {
var artist = x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue,
doc = loadXMLDoc("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist="+artist+"&api_key=83e386b0ba08735e3dee9b118478e56d&lang=en"),
bio = doc.getElementsByTagName("bio")[0].getElementsByTagName("summary")[0].childNodes[1].nodeValue;
bios[i] = bio; // store it in the array
document.write("<div><button type='button' onclick='document.getElementById("+i+").innerHTML=bios["+i+"];'>Open Bio</button></div>");
}
Of course, while that will work it's a bunch of bad practises, including
unsecured accessing of DOM nodes/properties. If the xml changes its format, you will get lots of exceptions here. You might be sure now that this never happens, but wrapping artist and bio in try-catch might not be a bad idea.
snychronous Ajax. One can do better than that.
loading 20 documents (and that sequentially!) even if you don't need them. It might be worth to try loading each of them only when the respective button is clicked.
document.write
Inline attribute event handlers
…and creating them even by JS.
I'm trying to create a new folder with an ascending number on the end if a folder already exists, but I end up in an infinite loop
var i=1;
while (myFolder.exists == true) {
var myFolder = new Folder(wf+"/"+curFile+"_folder"+i)
i++;
};
Any help would be appreciated.
It looks like myFolder.exists is a method, not a property, so you have to call it:
while (myFolder.exists()) {
var myFolder = new Folder(wf + "/" + curFile + "_folder" + i);
i++;
};
Otherwise, you would be evaluating the method itself, which is indeed always true in a boolean context.
Note in passing that redefining myFolder inside the loop is probably not the problem here. Loops in Javascript share the same scope as the enclosing code, and the variable will be hoisted to the start of that scope. As jdwire says, it can be undefined initially, but then you would receive an error instead of triggering an infinite loop.
I am trying to get the values of several fields & add them together & in my testing I am having problems. I have this code:
var count;
function calculate() {
// Fix jQuery conflicts
jQuery.noConflict();
count = 0;
jQuery('.calculate').each(function() {
var currentElement = jQuery(this);
var value = currentElement.val();
var count = count + value;
alert(count);
});
}
I enter in the value of "9" in my first field & when the first alert triggers I get "undefined9"; all the other values are currently set to "0"; when it triggers again I always get "undefined0".
Why am I getting the "undefined" bit & why is it only returning the value of the current field & not adding them together?
You are dimensioning the count value inside the loop, essentially setting it to undefined first in each iteration.
You want to remove the var within the loop. This way, it doesn't have scope to the anonymous function and JavaScript will look at the parent function for its declaration.
It may also be a good idea to parseInt(count, 10) the number first, because JavaScript overloads the + operator to mean arithmetic addition and string concatenation, and you wouldn't want count to be "0something".
Finally, count += value is easier to read :)
You're accidentally re-declaring count:
var count = count + value;
should be:
count = count + value;
The count declared in the inner-most scope (that of calculate) will hide the other one (this is called "shadowing" of variables).
The reason you get "undefined9" is because the default value of the newly-declared count variable is undefined; when you add to it, it sees an undefined value on the left, and a number on the right, and decides that string concatenation is the best way to perform the addition, resulting in the string "undefined9".
It has to guess at your intended meaning since + is overloaded to mean both numerical addition and string concatenation; in this case, it guesses wrong.
You're defining count in two different scopes - the calculate function, and then in the function that each is using. You may want to have the second count be named something else, or at least don't redeclare it.