简体   繁体   中英

Using value from input field as key in js object

I want to take input from user into input field and after extracting the value, I want to add this in a js object with key. My code:

 <!DOCTYPE html> <html> <body> <input type="text" id="task"> <button onclick="add_ele()">add</button> <p id="para"></p> <script> var l={} var count=0; function add_ele(){ var x = document.getElementById("task").value; var count=count+1; var pair= {count:x}; l={...l,...pair}; document.getElementById("para").innerHTML = JSON.stringify(l); } </script> </body> </html>

Output which I am getting:

电流输出

The desired output is

l={1:"some message from input text",
   2:"some message from input text", .. and so on}

But output which I am getting is {"count":"some text"}

Why this count is not replaced by count value which I am incrementing?

I think you want something like this. You receive an array with objects.

 var a = []; function add_ele() { var x = document.getElementById("task").value; //Adding object to array. The key is the array length + 1 a.push({ [a.length+1]: x }); document.getElementById("para").innerHTML = JSON.stringify(a); }
 <input type="text" id="task"> <button onclick="add_ele()">add</button> <p id="para"></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM