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?

3
  • var ss_+x - what should that do? Have you had a look at your browser's error console while running the above code? Commented Sep 10, 2018 at 8:55
  • 3
    simply make the var an array and push the values to it. var ss = []; - then ss.push($('input....val()); Commented Sep 10, 2018 at 8:55
  • Possible duplicate of Variable variables in JavaScript Commented Sep 10, 2018 at 9:48

2 Answers 2

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">

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Welcome, Glad I could help.
@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, ...
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]);
// ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.