Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep button from submitting form Javascript

I'm learning JavaScript and am unable to make a button inside of a form that doesn't submit the form. There is a similar question here but the most popular answer to specify type="button" doesn't work in my case and other answers involve jQuery, which I would like to leave out for now.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<script type="text/javascript">
        function submit(){
                alert("Yo")
        }
</script>
</head>

<body>
<form name="myForm" onsubmit="submit()">
        <input type="button" value="Submit!" onClick="submit()" />
</form>
</body>
</html>
like image 267
MANA624 Avatar asked Jul 10 '16 21:07

MANA624


People also ask

How do I stop submit button from submitting?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

How does JavaScript prevent a form from being submitted?

Use the return value of the function to stop the execution of a form in JavaScript.

How do I stop a form from submitting in HTML?

The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.

How do I stop a form from refreshing after submitting?

Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.


1 Answers

Since you're not using a type="submit" the only reason your form would submit anything is because you're literally calling the submit() method when the button is clicked. (well, sort of. It's actually form.submit() - the method you created is window.submit()).

By default, an input of type="button" will not do a form submission unless you literally call form.submit()

like image 143
Tibrogargan Avatar answered Oct 17 '22 14:10

Tibrogargan