-1

I am trying to make a input field that submits when enter is pressed. When I try to use the submit() function I get the default page reset. I don't know how to cancel this. I have tried to use a event listener for submit and even passing a anonymous function into submit() but neither seems to work.

addTask.oninput = () => {
    window.onkeydown = (key) => {
        if (key.keyCode === 13) {
            newTaskForm.submit()
            console.log(newTaskForm.addTask.value)
        }
    }
}

PS: if u think it is one of those I have already tried please say so. could have just messed up some syntax.

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • 2
    So.. you want to submit the form on enter yet prevent submit all together? – JavaScript Jul 14 '20 at 11:23
  • no i want to prevent reseting the page. thats what the function does isnt it ? – Tomáš Čikovský Jul 14 '20 at 11:24
  • `submit` submits the form to the page in the forms `action` or itself if not set. Sounds like it is doing what it should. Else you might want to use xhr. – JavaScript Jul 14 '20 at 11:26
  • @TomášČikovský the page must redirect to submit the data to the server unless you submit the data with an ajax request. – John Jul 14 '20 at 11:26
  • let me explain again. I want to submit the form and then use data from it on the same page. When we submit a form with a button we use a preventDefault() function to prevent the page from reloading right? so i am asking how to use this function when using the submit() function instead of a button – Tomáš Čikovský Jul 14 '20 at 11:34
  • 1
    If you use `preventDefault()` you don't prevent the *reload* you prevent *the form submission*. It's the form submission itself which causes you to go to a new location based on the form's `target`. If the target is the same page, then the submission will hit the same URL and just reload the page but you'd lose all the data. If you want to submit *and* stay, most likely you need to employ AJAX to send the data to the back end. – VLAZ Jul 14 '20 at 11:45

3 Answers3

0

addTask.oninput = () => {
    window.onkeydown = (key) => {
        key.preventDefault();
        if (key.keyCode === 13) {
            newTaskForm.submit()
            console.log(newTaskForm.addTask.value)
        }
    }
}

key is actually an event in your code.

If you want to not submit your form after a .submit()

then you can use :

newTaskForm.addEventListener('submit', (e) = > {
  e.preventDefault();
})
Angel
  • 100
  • 8
0

yes so my fault i actually dont know what happend but i tried the answer before even submitting the question and it didnt work, probably just made some stupid mistake. sorry i wasted your time :D

  • So it does work now? If so, please mark this answer as complete or delete the question to not confuse other people. – Rafael Jul 14 '20 at 11:44
0

The submit function works like that and will always do that. So I should not use it and save yourself with javascript.

Migats21
  • 176
  • 11