1

why this does not work?? I think it is logically correct.

P.S: I am new to JavaScript.

JavaScript part:

var i;
for(i=1; i=3; i++)
{
    var bbb[i] = document.querySelector('.txtt[i]');    
    console.log(bbb[i].value);
}

Html Part:

<input type="text" id="txtt1" class="txtt1" value="">
<input type="text" id="txtt2" class="txtt2" value="">
<input type="text" id="txtt3" class="txtt3" value="">

expectation: bbb[i] should contains the value of the particular input element as every time loops run a new variable should be created.

Actual: console shows error

SyntaxError: unexpected token: '['

1
  • You can define an array and push on to it var bbb = [] and then in the loop bbb.push(document.querySelector...). Also note that variables are not automatically interpolated into strings like '.txtt[i]'... Commented Feb 18, 2019 at 18:28

3 Answers 3

4

There are a couple problems. First, check your for loop. I think you meant it to be this instead:

for(i=1;i<=3;i++)

Also, I think you want this one line to be this instead:

var bbb[i]=document.querySelector('.txtt'+i);

Is this what you meant to do?

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

Comments

4

You have a few problems with your code:

  1. In your for loop you have no stop condition, The code you wrote will only get into the for loop if "i == 3", Your goal is to run the loop for as long as i is smaller then or equals to 3 "i<=3"

  2. In this part of your code:

    var bbb[i]=document.querySelector('.txtt[i]');
    

You initialize the "bbb" array each time you run the loop, it should be first initialize outside of the for loop and your use of the "i" variable is wrong so you will actually use the same text every time regardless of the value of "i"

  1. the console.log should just get bbb[i] and not bbb[i].value

This code will work:

var bbb = [];
for(var i=1 ; i<=3 ; i++)
{
    bbb[i]=document.querySelector('.txtt'+i);    
    console.log(bbb[i]);
}

Comments

4

Your for loop was wrong and make element id using concatenation('+') for selection

var i;
var bbb=[];
for(i=1;i<=3;i++)
{
bbb[i]=document.querySelector('.txtt'+i+'');    
console.log(bbb[i].value);
}
<input type="text" id="txtt1" class="txtt1" value="a">
<input type="text" id="txtt2" class="txtt2" value="b">
<input type="text" id="txtt3" class="txtt3" value="c">

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.