将输入值推送到JSON数组中

时间:2016-03-01 16:48:14

标签: javascript html arrays json

我正在尝试将一些值从输入文本框推送到JSON数组。这是我试过的

代码:

<!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>

所以我试图推动&#39; x&#39;通过定义变量(x)来获取输入文本框的值:

进入数组
x = document.getElementById("studentnumber").value;

尝试将其推上第25行:

obj['G11S'].push({"StudentNumber": "4","status": "Member"});

1 个答案:

答案 0 :(得分:4)

您必须获取输入值并将它们存储在对象变量中,然后将该变量推送到JSON数组中:

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);
}