1

So I want to pass a variable like : childage_error1 childage_error2 childage_error3 etc. And I have this code right here:

for (var i = 0; i < gyermekek; i++) {
      document.getElementById('gyermekkor_error' + (i + 1) + '').innerHTML = response.window['gyermekkor_error'+i+1]
    }

If I put manually "gyermekkor_error1" it works but it wont work in a loop. It works in getElementById but not in the end.

5
  • Try with var i = 1 then you can just use i lower down, instead of i + 1 Commented Jul 15, 2022 at 13:18
  • 1
    console.log('gyermekkor_error'+i+1) should be able to quickly show you where your mistake lies. And the solution is contained in your code already as well. (Why are you doing the same thing in two different ways to begin with?) Commented Jul 15, 2022 at 13:19
  • What is the error? Are you looping one too many times? Commented Jul 15, 2022 at 13:25
  • 'gyermekkor_error01' How i make the 0 disappear? Commented Jul 15, 2022 at 13:26
  • I already told you the solution - see the very first comment. Commented Jul 15, 2022 at 13:29

1 Answer 1

1

response.window['gyermekkor_error'+i+1]

You are adding a string to a number plus a number. Basic order of operations left to right. The code does not assume you meant to add i to 1 first.

So you are getting

'gyermekkor_error01'
'gyermekkor_error11'
'gyermekkor_error21'
'gyermekkor_error31'

You need to surround the addition part with parenthesis

response.window['gyermekkor_error' + (i+1)]

Or just start your loop off at one so you do not need the addition step.

for (var i = 1; i <= gyermekek; i++) {
  var key = 'gyermekkor_error' + i;
  document.getElementById(key).innerHTML = response.window[key];
}
Sign up to request clarification or add additional context in comments.

2 Comments

(index):410 Uncaught TypeError: Cannot read properties of undefined (reading 'gyermekkor_error1') at ajax_request.onreadystatechange but if i try like this: response.gyermekkor_error1 It gives me the AJAX response.There is no difference or is there?
response.window.gyermekkor_error1 does not equal response.gyermekkor_error1. You are saying your object is like { "window": { "gyermekkor_error1": "foo" } }. You read some answer about global variables and bracket notation and thought you needed window? Just use response[key]

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.