0

I have a problem. Was working on this for a long time, but really stuck. Searching in stackoverflow for similar problems did not really help me - as people have a little different issues and I could not implement the answers to my code.

I have a dynamically changing <input> elements, where their ids and values are created by PHP. So, total number <input> elements there can be 1 or even 10+.

HTML:

<input id='photonumb1' type='text' value='001'/> 
<input id='photonumb2' type='text' value='002'/> 
<input id='photonumb3' type='text' value='003'/> 
...

There is also one <input id="totalphotos" /> tag which has a value of how many <input> elements there are created.

I want JavaScript to take the number of <input> elements there are (probably taking a value from "totalnumbers") and take the values of all "photonumb*" (using for() loop I suppose?). Each value of each element is to be assigned as new variable, like:

var photoname1 = 001;
var photoname2 = 002;
var photoname3 = 003;
...

Total variable number depends on how many <input> elements there are created.

I was trying to do the suggestions, like:

totalphotos = document.getElementById('totalphotos').value;

for (i = 1; i <= totalphotos.length; i++) { 
    window[photoname + i] = document.getElementById('photonumb' + i).value;
}

But this did not help me, it just does not create a new variable, if I do console.log(photoname1); for example.

Anyone has a suggesstion for me? Thank you in advance!

----- EDIT--- Hey @Quentin, why marked as duplicate? Maybe the idea of the question might be similar, but I am asking it completely other way, so even the answer that I am looking for is different. Moreover, I have seen that question before, I could not completely understand how it works. Thus for other beginners like me, this question might be way more useful. Thanks.

2 Answers2

1

The window['here'] variable was not "named".

totalphotos = document.getElementById('totalphotos').value;

for (i = 1; i <= totalphotos.length; i++) { 
    window['photoname' + i] = document.getElementById('photonumb' + i).value;
}

Beware also, that the script is executing immediately, so you have to put the script at the end of the HTML.

metadings
  • 3,798
  • 2
  • 28
  • 37
  • Hey! That worked smoothly! Thanks a lot, your answer is accepted. By the way, I use this script in `$(document).ready(function (){`, is it also ok, or I still should put the script at the end of HTML? Sorry for asking a dumb question, I'm a beginner. – StartedFromTheBottom Dec 11 '14 at 12:43
  • 1
    Yes, that's fine! Use `jQuery(function ($) { })` or `jQuery(document).ready(function ($) { })` - they are the same. – metadings Dec 11 '14 at 12:44
0

You might have a mistake in the For Loop.

You are comparing i to the length of totalphotos, but it already is the number of the Photos

Try

for (i = 1; i <= totalphotos; i++) { this["photoname" + i] = document.getElementById('photonumb' + i).value; }

Anders Anderson
  • 433
  • 3
  • 8