0

I want to push the Javascript object using a loop And Getting the value of input using jQuery.

var data = {name: "Grace"};

$("#test").on('change', function () {
  
      console.log($('"#test'+1+'T"').val());
  
      for(var i=1; i<= 2; i++){
        data['Thomas'+i+'Shelby'] = $('"#test'+i+'T"').val();
      }
      console.log(data);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<input type="text" id="test1T">
<input type="text" id="test2T">
<input type="text" id="test">

Syntax error, unrecognized expression: "#test1T"

**Expected Output: **

If user input Arthur in #test1T, John in #test2T and Micheal in #test.

Then It should console log following object:

{
 name: "Grace",
 Thomas1Shelby: "Arthur",
 Thomas2Shelby: "John",
}

1
  • Where is the Micheal ? Commented Jan 20, 2021 at 8:54

2 Answers 2

2

It's error in query selector. Don't put " inside.

change $('"#test'+i+'T"').val()
to be $('#test'+i+'T').val()

var data = {name: "Grace"};

$("#test").on('change', function () {
  
      console.log($('#test'+1+'T').val());
  
      for(var i=1; i<= 2; i++){
        data['Thomas'+i+'Shelby'] = $('#test'+i+'T').val();
      }
      console.log(data);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="test1T">
<input type="text" id="test2T">
<input type="text" id="test">

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

Comments

1

Quotes issues. A valid ID selector would look like

$('#test1T') or $('#test'+i+'T')

I suggest template literals

const data = {
  name: "Grace"
};

$("#test").on('change', function() {
  for (var i = 1; i <= 2; i++) {
    data[`Thomas${i}Shelby`] = $(`#test${i}T`).val();
  }
  console.log(data);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<input type="text" id="test1T">
<input type="text" id="test2T">
<input type="text" id="test">

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.