I'm trying to generate form elements with jQuery to send to a Paypal form, I'm having issues looping through an array.
The list of items in a shopping cart is held in an array, the Javascript loops through the array adding the form fields and values as follows
for (j=0;j<(itemArray.length);j++)
$('#createFields').append("<input type='hidden' name='item_name_"+ j +"' value='"+itemArray[j]+"'/>");
This works perfectly, except, I need item_name_ to begin with a 1, not a 0.
"easy" I thought
for (j=0;j<(itemArray.length);j++)
$('#createFields').append("<input type='hidden' name='item_name_"+ j+1 +"' value='"+itemArray[j]+"'/>");
Should work, but no, that gives 01.
So I figured it wasn't treating "j" as integer
So I tried
(j*1)+1
That still gave me 01
parseInt(j)+1
Also gives me 01!
How can I get "0+1 = 1" from this counter variable?!
I can't understand why this issue is happening, I've got over the same problem with the methods above many times before!
I've also tried
for (j=1;j<( (itemArray.length+1) );j++)
but that just screws up the looping
Just group the expression:
"..." + (j+1) + "..."
this will give j + 1 a higher precedence so that it is evaluated first and then concatenated.
Otherwise, concatenation with the string will take place first, that is, first j is concatenated with the preceding string and then the resulting string is concatenated with 1 (left to right evaluation). Without grouping, the expression is implicitly evaluated as:
((("..." + j) + 1) + "...")
try
for (j=0;j<itemArray.length;j++)
{
$('#createFields').append("<input type='hidden' name='item_name_"+ (j+1)
+"' value='value='"+itemArray[j]+"'/>");
}
Another solution:
for (j=1;j<=itemArray.length;j++)
{
$('#createFields').append("<input type='hidden' name='item_name_"+ j +"'value='value='"+itemArray[j-1]+"'/>");
}
Related
This question was asked before: Trouble understanding what happens during javascript for loop
but the asker didn't get the right answer and so did I. I learn C++ and Python earlier so I get familiar with loop but when I practing this code:
let text = "";
let i;
for(i=0; i<5; i++)
{text += "The number is " + i + " ";}
document.write(text);
the output is totally different to what I expected. I visited W3schools but I can't find the answer
https://www.w3schools.com/js/js_loop_for.asp
https://www.w3schools.com/js/tryit.asp?filename=tryjs_loop_for_om3
I expected the output is "" because text can't be changed but the code prints out: "The number is 0 The number is 1 The number is 2 The number is 3 The number is 4". My question is why the print executes in the loop though the print is outside the loop? Thank you very much!
The print executes as you expect: Only once at the end. In the loop, each time an extra part is appended to text. That is:
[iteration 0] ""
[iteration 1] "The number is 0 "
[iteration 2] "The number is 0 The number is 1"
[iteration 3] "The number is 0 The number is 1 The number is 2"
etc.
Then in the end, you print the final String which is the concatenation of all the partial Strings you 'glued' together.
Saying x += y is the same as saying x = x + y. Standard variables (var and let) are still mutable, so if you initialize it as an empty String, you can still append/replace it later.
Try making text a const instead, and there should be a runtime TypeError because you try to reassign a constant.
why the output not empty string because the text variable not empty anymore after for loop. you have assign string when loop so the text variable not empty anymore
This is the Code Sandbox: https://codesandbox.io/s/rw0j2orqmp
The file this is in is reducers.js
I'm building a React/Redux calculator app, and currently I'm in the process of making the output display the results of the current calculation held in state. It works without parentheses but calculates the whole formula rather than a piece at a time. To fix this I wanted to wrap each piece in parentheses to have it calculate separately, taking off the method and then sticking it back on when the first part is finished calculating by doing this:
value:
methods.indexOf(state.lastValue) < 0
? eval("(" + state.calc.slice(0, -1) + ")" + state.calc.slice(-1) + state.value)
: state.value,
but when I have it like that, I get "Unexpected token ) " .
Is there an easier way to accomplish what I'm trying to do, and or is there a functional replacement for eval() in this case?
I'm not sure why you're using eval or parentheses here. Is there a reason why this won't work for you?:
methods.indexOf(state.lastValue) < 0
? state.calc.slice(0, -1) + state.calc.slice(-1) + state.value
: state.value
If you need to group things together, just use parentheses without the eval.
methods.indexOf(state.lastValue) < 0
? ((state.calc.slice(0, -1)) + state.calc.slice(-1) + state.value)
: state.value
Update: I see what you're saying, sorry, it was hard to understand from your original explanation and I was on my mobile and couldn't really inspect your sandbox.
I'm thinking it may be better to keep a string that you can evaluate simply later, for example, if you have "7 + 3" stored and press *, turn wrap that original string in parentheses and add the *, resulting in "(7 + 3) *", etc. Then whenever you want to show the result, you just evaluate that single stored calculation.
If you insist on doing eval that way, I'll just tell you that it works. For example, try this in the console:
eval("(" + "7 + 3" + ")" + "* 2")
// 20
So you may be doing something wrong with the values you are returning from the slice, which results in an eval error.
Try console logging that whole expression to see what's actually going on.
$.getJSON("urlhere", {}, function(data)
{
// Other code is commented out, I'm just using the following loop to test.
for(var a = 0; a < 2546; a++)
if(a > 995)
alert((a + 1) + ": " + data.d.results[a].Column2);
});
For some reason, I wasn't getting all the things from my list that I needed. So I put in this loop to test it and it stops at 1000 for some reason. Why does this happen and how do I fix it?
SharePoint only returns 1000 results per "page." If you look, there should be a "link" element in there near the bottom of the JSON that contains a link to the next 1000 results.
That's how it is when it returns XML, anyway. Haven't tried JSON, but I'm sure it's similar.
'urlForListData' + '?$filter=Building eq \'' + building + '\''
I found out that you can filter the list for what you need so that it never exceeds 1000, which was much simpler than what I was doing before. Of course, Building is a column in the SharePoint list and building is a variable holding the requested building number.
Doing some javascript self-learning and the program itself is very simple. It searches through the input for keywords and when it finds it, it places the index values into list placeholders. (I'll develop later code to remove repetitions).
However, a snag. I'm trying to do something very simple. All I'm doing is assigning the variable words5 to keywords[n].length. Now I've discovered the keywords[n].length does print me the correct value when nested into document.write(). I've also discovered that keywords[n] also prints the correct value when nested into document.write(). BUT if either are used in the code outside of a document.write, it causes the code to break.
Been going at it for hours. And I haven't been able to find a solution. Do you guys have any clues? The code that I used to test it out is commented out.
<html>
<body>
<script type="text/javascript">
function separate()
{
contents = document.myForm.event.value;
placeholders = [32342423, 253234523];
keywords = [" in ", " at ", " on ", " for "];
for(n=0;n<=keywords.length;n++)
{
for (i=0;i<=contents.length;i++)
{
//document.write(i,"+", i+keywords[n].length, keywords[n])
//document.write(keywords[n].length)
word5 = (keywords[n].length);
//document.write(" " + contents.slice(i,i+word5) + " ")
//if (contents.slice(i,i+4) == " at ")
//if (contents.slice(i,i+wordlength) == " at ")
//if (contents.slice(i,i+4) == keywords[n])
if (contents.slice(i,i+word5) == keywords[n])
{
placeholders.push(i);
}
}
}
document.getElementById("sliced").innerHTML = placeholders;
printer();
}
function printer()
{
contents = document.myForm.event.value;
document.getElementById("MSG").innerHTML = contents;
}
</script>
<form name="myForm" method="post">
Add Event: <input type="text" name="event" value="Whatever at hello at crazy" /><br />
<input type=button value="Submit" onClick="separate()" />
</form>
<SPAN ID="sliced"> </SPAN>
<p></p>
<SPAN ID="MSG"> </SPAN>
</body>
</html>
Any help is greatly appreciated. Saviours really =)
The eror I get when I run your code is that:
wordlength is undefined
This is causing the code to fail. Where are you defining wordlength?
Update
Also be aware that when you're looping through arrays that arrays have a zero index. That is, the first item in the array is item 0. The count of the number of items in the array is always going to be greater than the sum of the indexes (index sum + 1).
This basically means that when you use the <= (less than or equel to) operator in your for loop, you're looping from zero to the number of items in your collection, however, since your array index begins are zero, you're eventually going to be requesting an item from your array that doesn't exist.
To ensure that you only loop over the available items use the < operator rather than <=.
that's not what's breaking your code, it seems like you are not defining the variable "wordlength" anywhere on your code, this is what's breaking your code.
word5 = (keywords[n].length) actually works.
Also I would recommend getting "firebug" addon for firefox, it's the best way to debug any javascipt or html code, use the console to output your debug statements using "console.log(myvar)" instead of document.write which is a pretty old fashioned way of doing things.
Let me know if this solution doesn't work for you :)
EDIT:
I did another set of tests and found out what the reason was, your first loop is running 1 more than what your current number of arrays are, so instead of making it "less than or equal too" it should just be less than:
for(n=0;n<keywords.length;n++)
Hence why you're getting a keywords[n] is undefined, as there is no keywords[4] in the array
just trying to test for equality in this piece of code, but getting a fail.
<input type="text" name="dave_blah"/>
<input type="text" name="dave_bleh"/>
I then access the name values of each of these inputs and assign them to two variables, name1 and name2. I then extract the first part of the name,delimited by a "_".
var oldName = name1.name.split('_',1);//dave
var thisName= name2.name.split('_',1);//dave
alert(oldName);
alert(thisName);
if(oldName !== thisName){//if "dave" is not equal to "dave"
alert("name difference = "+ oldName + " " + thisName);
}
Yet, when running this code, the message alerts regardless (I've tried != too). In principle, the alert shouldn't execute. It's quite late in the evening, so it's probably obvious, but can someone point this noob in the right direction? If I remove the not operator from the if statement - the function works as desired.
thisName and oldName are both arrays, do something like this:
var oldName = name1.name.split('_',1)[0]; //dave
var thisName= name2.name.split('_',1)[0]; //dave
And I think it should work.
OK. I've sussed the problem. The comparison was seeing the participants in the test both as Objects, as opposed to the string value of the contents. So, I solved it by casting the results to a string.