1
var x = 1;
var ctr = 5;
while (x<=ctr){
    var ss_+x = $('input[name=IDMenu_'+x+']').val();
    x++;
}

As you can see above I have a loop that will iterate through input fields with the name IDMenu_1 through to IDMenu_5. I attempted to make the variable names themselves variable by using the syntax var ss_+x; however this is incorrect and does not work.

If I were to not use a loop, this is what I would be doing:

var ss_1 = $('input[name=IDMenu_1]').val();
var ss_2 = $('input[name=IDMenu_2]').val();
var ss_3 = $('input[name=IDMenu_3]').val();
var ss_4 = $('input[name=IDMenu_4]').val();
var ss_5 = $('input[name=IDMenu_5]').val();

Is it possible to accomplish this within a loop?

Scoots
  • 3,048
  • 2
  • 21
  • 33
ICG DEVS
  • 195
  • 3
  • 15
  • `var ss_+x` - what should that do? Have you had a look at your browser's error console while running the above code? – Nico Haase Sep 10 '18 at 08:55
  • 3
    simply make the var an array and push the values to it. `var ss = [];` - then `ss.push($('input....val());` – Jeff Sep 10 '18 at 08:55
  • Possible duplicate of [Variable variables in JavaScript](https://stackoverflow.com/questions/8869187/variable-variables-in-javascript) – Scoots Sep 10 '18 at 09:48

2 Answers2

2

You're trying to create variables with dynamic names so you could use window[variable_name].

NOTE: IMO you could use an array of values instead in this case.

var x = 1;
var ctr = 5;

while (x <= ctr) {
  window["ss_" + x] = $('input[name=IDMenu_' + x + ']').val();
  x++;
}

console.log(ss_1, ss_2, ss_3, ss_4, ss_5);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input name="IDMenu_1" value="10">
<input name="IDMenu_2" value="20">
<input name="IDMenu_3" value="30">
<input name="IDMenu_4" value="40">
<input name="IDMenu_5" value="50">
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • This is working and I prefer this one than using array, I don't know which is better but for me this is more simple than using array. Thanks. – ICG DEVS Sep 10 '18 at 09:08
  • Welcome, Glad I could help. – Zakaria Acharki Sep 10 '18 at 09:14
  • 1
    @ICGDEVS Also, you could consider not putting all your variables in the global scope, only create one `ss` object that will contain your properties, by doing the following : `var ss = {}; while(...){ ss[x] = ...};` and then access them with `ss.1, ss.2, ...` – Logar Sep 10 '18 at 09:47
2

It'd be better to make the var an array, then push the items to it.

var x = 1;
var ctr = 5;
var ss = [];
while (x<=ctr){
   ss.push($('input[name=IDMenu_'+x+']').val());
   x++;
}  

You'll then have the values in

console.log(ss[0]);
console.log(ss[1]);
// ...
Jeff
  • 6,895
  • 1
  • 15
  • 33