1

I am trying to push some values from the input textbox to the JSON array. Here is what i tried

Code:

<!DOCTYPE html>
<html>
<body>

<input id="studentnumber" placeholder="Student Number"></input>
<input id="status" placeholder="Status"></input>
<button id="bt1" onclick="newUser()">Validate</button>
<p id="demo"></p>

<script type="text/javascript">

//Array
var jsonStr = 
    '{"G11S":[{"StudentNumber":"1","status":"Pass"},{"StudentNumber":"2","status":"Pass"},{"StudentNumber":"3","status":"Pass"}]}';


function newUser(){

    x = document.getElementById("studentnumber").value;

    //Debug
    console.log(x);

    var obj = JSON.parse(jsonStr);
    obj['G11S'].push({"StudentNumber": "4","status": "Member"}); // <~~ What am I Supposed to replace the "4" with and the "Member aswell"

    jsonStr = JSON.stringify(obj);
    console.log(jsonStr);
}


</script>

</body>
</html>

So I am trying to push 'x' into the array by defining a variable (x) to get the input textbox's value:

x = document.getElementById("studentnumber").value;

Trying to push it on line 25:

obj['G11S'].push({"StudentNumber": "4","status": "Member"});
3
  • Its due to the defined variable ' x ', being placed in the statement that pushes data in at line 25 Commented Mar 1, 2016 at 17:03
  • try my answer, is this what you want? If not can you make it a little bit clear of what you need? Commented Mar 1, 2016 at 17:05
  • @Akis_Tfs **Thank you for your help brother ** works like a charm! Commented Mar 1, 2016 at 17:09

1 Answer 1

5

You will have to get the input values and store them in an object variable then push that variable in the JSON array:

function newUser(){
  var user = {};

  user.StudentNumber = document.getElementById("studentnumber").value;
  user.status = document.getElementById("status").value;

  //Debug
  console.log(user);

  var obj = JSON.parse(jsonStr);
  obj['G11S'].push(user);

  jsonStr = JSON.stringify(obj);
  console.log(jsonStr);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You @Akis_Tfs !

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.