MANA624 MANA624 - 4 months ago 14
Javascript Question

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>

Answer

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()