-1

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:

current output

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?

Reporter
  • 3,897
  • 5
  • 33
  • 47
Mohammed Mak
  • 47
  • 1
  • 7
  • 3
    Please post your code as text, not an image of text. – Scott Hunter Jul 19 '21 at 12:13
  • First mistake: You made `count` a _local_ variable inside your function, so it is uninitialized when you tried to add 1 to it, so the result will always be `undefined`. – CBroe Jul 19 '21 at 12:21
  • Second: Object key names written like this, are always meant “literal”, if you want to make them dynamic based on the content of a variable, you need to do it like this, https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name – CBroe Jul 19 '21 at 12:22
  • Looks like what you need is an array, not an object, for `l`. – connexo Jul 19 '21 at 12:22
  • And third, you are _replacing_ the innerHTML of your output element on each call; if you want that output to accumulate, then you need to use `.innerHTML += …` – CBroe Jul 19 '21 at 12:22

1 Answers1

0

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>
alexP
  • 3,672
  • 7
  • 27
  • 36
  • if I change my {count:x} in my previous code to { [count] :x } it works properly. What will be the need of [] this brackets. Why only count doesn't works. – Mohammed Mak Jul 19 '21 at 12:58
  • `[count]` output the value of `count` and doesn't use the word "count" for key. – alexP Jul 20 '21 at 06:34
  • But theres no need for counting. Look at my edited answer. – alexP Jul 20 '21 at 06:40