Stop form submit with native javascript

2019-01-29 03:30发布

I need to select a form via native javascript (not jQuery) and prevent the form submission (preventDefault).

The trick is that the form does not have a name or id, and cannot be assigned one.

My HTML:

<div id="search">
    <form method="get">
        <input type="text" name="post"/>
        <input type="submit" value="Post">
    </form>
</div>

So far, I have tried to use document.forms[0] and document.getElementsByTagName("form")[0] to select the form, but the value returned is undefined.

Another possible solution is to overload the functionality of the submit button, but I did not have success with that either.

3条回答
Bombasti
2楼-- · 2019-01-29 03:39

on form submit just return false.

e.g. <form onsubmit="return false">

查看更多
Bombasti
3楼-- · 2019-01-29 03:44

Simple way is use onsubmit event handler

<script>
var submitHandler = function() {
  // your code
  return false;
}
</script>

<form method="get" onsubmit="return submitHandler()">....</form>

or more easy

<form onsubmit="return false;">
查看更多
甜甜的少女心
4楼-- · 2019-01-29 03:49

Using querySelector and an event listener, it's almost like jQuery

document.querySelector('#search form').addEventListener('submit', function(e) {
    e.preventDefault();
});

note that the script has to come after the elements, or use a DOM ready handler, so the elements are available.

FIDDLE

查看更多
登录 后发表回答