I am trying to store input values from an HTML form using JavaScript. I have the result I am looking for but not certain if it is the correct or most efficient way, as each time I press submit, it loops through and increase the array, but also the console log duplicates by one.
I am already quite aware that I have two console logs, that is not the question.
let inputArr= [];
document.getElementById("submit-btn").onclick = function submitFormVal(event){
event.preventDefault();
let inputVal;
inputVal = document.getElementById("form-val").value;
console.log(inputVal);
inputArr.push(inputVal);
for(let i =0; i < inputArr.length;i++){
inputArr[i];
inputArr = inputArr.map(Number);
console.log(inputArr);
};
};
<form id="form-test">
<input type="number" id="form-val" value="1">
<button id="submit-btn">Submit</button>
</form>
Your console.log()
is inside your loop. As the array grows, the loop iterates more and so you get more logging of the same array.
Move it so that it runs after the loop and use console.clear()
at the beginning of the function so you only see the newest data.
Also, don't use a submit
button if you aren't actually submitting any data anywhere. Just use a regular button and then you don't need to worry about cancelling the submit
event.
Lastly, use modern standards. onclick
(an event property) limits your ability to work with the event. Instead use .addEventListener
let inputArr= [];
document.getElementById("submit-btn").addEventListener("click", function(event){
console.clear(); // clear out old data
let inputVal;
inputVal = document.getElementById("form-val").value;
console.log(inputVal);
inputArr.push(inputVal);
for(let i =0; i < inputArr.length;i++){
inputArr[i];
inputArr = inputArr.map(Number);
};
console.log(inputArr);
});
<form id="form-test">
<input type="number" id="form-val" value="1">
<button type="button" id="submit-btn">Submit</button>
</form>
Now, with all that in mind, the real solution here is much simpler than what you are doing. There is no need for a loop that creates a new array of numbers with one more item in it. All you have to do is .push
the new data (with a simple number conversion) into the existing array. Also, get your DOM reference just once before the button is pressed so you don't have to keep finding it every time the button is pushed.
let inputArr= [];
// Get your DOM reference just once, not every time you click the button
let inputVal = document.getElementById("form-val")
document.getElementById("submit-btn").addEventListener("click", function(event){
console.clear(); // clear out old data
inputArr.push(+inputVal.value); // the prepended + implicitly converts the string to a number
console.log(inputArr);
});
<form id="form-test">
<input type="number" id="form-val" value="1">
<button type="button" id="submit-btn">Submit</button>
</form>