i have this snippet. As a result i see an error: Invalid left-hand side in assignment.
var arr = [ "text1", "text2", "text3", "text4" ];
jQuery.each(arr, function(index, value) {
this = jQuery("#sc-dialog ."+value).val();
});
Does anyone can point me to how to fix this? Thanks.
This is an UPDATE I need that variable 'text' will have the numbers in the loop: text1, text2, text3... i have made it like this:
var arr = [ "1", "2", "3", "4" ];
jQuery.each(arr, function(index, value) {
var text + index = jQuery("#sc-dialog .text"+value).val();
});
But i got an error: Unexpected identifier. The problem is here: var text + index
3 Answers 3
Try like this:
jQuery.each(arr, function(index, value) {
arr[index] = jQuery("#sc-dialog ."+value).val();
});
Comments
Putting a + after your variable name is a syntax error in your var statement:
var text + index = jQuery("#sc-dialog .text"+value).val()
A valid variable declaration will be either variable name by itself:
var text;
Or the variable name with an assigned value:
var text = jQuery("#sc-dialog .text"+value).val();
The value being assigned can have a + or other operators in it:
var x = y + z - 5 * (a + b);
And in a single var statement you can declared multiple variables with or without values by separating them with commas:
var i, j = 0, k, text = jQuery("#sc-dialog .text"+value).val(), x = 12 + 4;
An array of numbers that follow a simple pattern (in this case array element index plus 1) is kind of pointless when you can achieve the same thing with a standard for loop. EDIT: from your comment it seems like you don't want to process the values within the loop, you want to store the values for later use. You mention wanting text1, text2, etc., but if you need to reference them individually it sounds like your various textareas aren't really a group and it doesn't make sense to process them in a loop at all. But if you insist then you should store the values in an array:
var i,
text = [];
for (i = 1; i <=4; i++) {
text[i] = jQuery("#sc-dialog .text"+i).val();
}
// later in your code
// text[1] is first value,
// text[2] is second value, etc
Note that JS array indexes are zero-based, and array .length is one more than the highest index, but your field numbering starts at 1 - keep that in mind if you later loop over the text array.
2 Comments
var text1 = $("#sc-dialog .text1").val(); var text2 = $("#sc-dialog .text2").val(); var text3 = $("#sc-dialog .text3").val();You can't use 'this' as a variable name. try something like:
var arr = [ "text1", "text2", "text3", "text4" ];
jQuery.each(arr, function(index, value) {
var dialogValue = jQuery("#sc-dialog ."+value).val();
});
this. What are you trying to do?this =supposed to mean?