0

I have a form that I want to eventually do some validation on. To test that I am successfully able to assign a value from the form to a variable in Javascript, I have this code:

<form method="get" id="form">
    <label for="newTask">New Task</label>
    <input type="text" name="task" id="newTask" required>
    <br>
    <input type="submit" value="submit" onclick="validate()"> 
</form>

<script>
    function validate(){
        var newTask = document.getElementById("newTask").value;
        console.log(newTask)
    }
</script>

When I click submit, the value I submitted into the "task" field does appear in the console, but then immediately disappears. I would like to ask why this is happening, and I don't want the console to clear. Is the value still stored in newTask after this runs? I'm not sure how to check that. I tried to use onsubmit="validate()", but then nothing seemed to happen in the first place.

Skunko
  • 1
  • 1
  • 1. Change submit button to type="button" OR 2. Use submit event of the form and preventDefault to not submit: `document.getElementById("form").addEventListener("submit", function(e) { e.preventDefault(); console.log(this.task.value); });` 3. (old fashioned): `
    – mplungjan Nov 12 '22 at 08:13
  • #2 is better because #1 will stop the enter key from working for submitting the form and it's also more logical that you want to validate a form when it is submitted. – CherryDT Nov 12 '22 at 09:17

0 Answers0