简体   繁体   中英

Javascript, page keeps refreshing

I'm trying to do something on submitting the form but when i open the page it keeps refreshing without me submitting or doing anything

<html>
<head>
</head>
<body>
    <form id="someForm">
        <input id="someInput" /><button>Send</button>
    </form>
    <script>        
  document.getElementById('someForm').submit(() => {
        //do something..
  });
    </script>
</body>
</html>

Your code is submittihng the form as soon as the page is displayed. Naturally, that redisplays the page, which submits the form again.

The problem is here:

document.getElementById('someForm').submit(() => { // <===
    //do something..
});

That calls the submit on the form, which submits it. If your goal is to hook the event, you don't do it that way (looks like you may have seen some jQuery examples), you do it like this:

document.getElementById('someForm').addEventListener("submit", () => { // <===
    //do something..
}, false);

Side note: There are definitely times you want to use an arrow function with event handlers, but much of the time, you don't want to, because you want the event system to set this for you to the element on which you hooked the handler. So just something to keep in mind.

document.getElementById('someForm').submit(() => {
      //do something..
});

The above code is telling the form to submit.

If your goal is to submit the form when you press the button it would look like this:

document.getElementsByTagName('button').click(function(){
    document.getElementById('someForm').submit()
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM