'How to clear input field after submitting form and push values into array (Vanilla JS)
Onclick of the button I would like to take the values submitted and index them in the empty array. As you can see in the bottom line I have used the reset method on the form but when logging the array, all of the indexes have an empty value.
I have also used preventDefault() to stop the form from submitting, could the form tags be causing the issue?
const enteredNumbers = [];
console.log(enteredNumbers);
const form1 = document.getElementById("form1");
form1.addEventListener("submit", e => {
e.preventDefault();
const values = document.getElementsByName("number")[0];
enteredNumbers.push(values);
form1.reset();
}, true);
<form id="form1">
<div class="row w-100 d-flex justify-content-between div1">
<div class="col-12 d-flex justify-content-center">
<input type="number" name="number" id="number" min="1" max="100">
</div>
<div class="col-12 d-flex justify-content-center">
<button type="submit" form="form1" id="submit">Submit</button>
</div>
</div>
</form>
Solution 1:[1]
The form tag does not causing this issue, but 2 other things does:
- Log the array after each time you submit, and not just on the first time the page renders (the first time the script runs).
- Your
valuesis an html element, not the value. The value iselem.value, that's what I pushed there.
Good luck
const enteredNumbers = [];
const form1 = document.getElementById("form1");
form1.addEventListener("submit", e => {
e.preventDefault();
const values = document.getElementsByName("number")[0];
enteredNumbers.push(values.value);
form1.reset();
console.log(enteredNumbers);
}, true);
<form id="form1">
<div class="row w-100 d-flex justify-content-between div1">
<div class="col-12 d-flex justify-content-center">
<input type="number" name="number" id="number" min="1" max="100">
</div>
<div class="col-12 d-flex justify-content-center">
<button type="submit" form="form1" id="submit">Submit</button>
</div>
</div>
</form>
Solution 2:[2]
I just relaized I forgot to add the value property to this:
document.getElementsByName("number").value
Sorry this can be closed
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Omri Attiya |
| Solution 2 | jordantocode11 |
