Reputation:
I have two HTML text input elements and one paragraph element. I have an empty javascript array and a function to push those two text input values as key:value into the array. I have a button to activate the function and print the array in the paragraph.
My javascript function is running but, the output is never producing [key:value],[key:value] but producing [object Object],[object Object]
HTML :
<input type="text" id="t1" />
<input type="text" id="t2" />
<button id="b1" onclick="add()">Push</button>
<p id="p1"></p>
JavaScript :
var t = [];
function add() {
var t1 = document.getElementById('t1').value;
var t2 = document.getElementById('t2').value;
t.push({key:t1, value:t2});
document.getElementById('p1').innerHTML=t;
}
How can I properly pushing key:value to this array and print it?
Update I ended up going with an Object
syntax that looks like this:
const m = {}
m[1] = 2
console.log(m, m[1])
Upvotes: 1
Views: 10857
Reputation: 4452
You push elements in array correctly, the problem is conversion to string. You can see array in console.
function add() {
var t1 = document.getElementById('t1').value;
var t2 = document.getElementById('t2').value;
t.push({key:t1, value:t2});
console.log(t);
}
Upvotes: 2
Reputation: 5363
var t = [];
function add() {
var t1 = document.getElementById('t1').value;
var t2 = document.getElementById('t2').value;
t.push({key:t1, value:t2});
render()
}
function render() {
var html = '';
t.forEach(function(element) {
html += element['key'] +' = ' + element['value'] + '<br/>';
})
document.getElementById('p1').innerHTML = html;
}
<input type="text" id="t1" /> <input type="text" id="t2" /> <button id="b1" onclick="add()">Push</button> <p id="p1"></p>
Upvotes: 1