Onsubmit update html form
I am trying to use Javascript to submit form data. Here is the html.
<form onsubmit="post();"> //input fields here </form> Here's the javascript for the post() function.
var post = function() { alert('the form was submitted'); return false; } My problem is that Javascript is working, but the form is still processing and refreshing the page.
I put the return false; code return false; in the hope that he will stop the form from updating.
You will need to put the returned false part after the post () function in the onsubmit handler, for example:
<form onsubmit="post();return false;"> //input fields here </form> Keep js out of the DOM.
<form id="myform" action="somepage.php" method="post"> //input fields </form> JQuery
$('#myform').submit(function(event){ alert('submitted'); event.preventDefault(); }); You need to return false from your built-in dom-0 handler. Therefore change
onsubmit = "post();"> to
onsubmit = "return post();"> Or you can specify your id form and do this:
<form id="form1" onsubmit = "post();"> Then from the safe place where your home is ready:
document.getElementById("form1").onsubmit = post; Since you added the jQuery tag, this is the best way to do this:
unobtrusive event binding
$('form').submit(function(){ alert('the form was submitted'); return false; }); In your opinion it should be;
<form onsubmit="return post();"> Since this post is tagged with jQuery, I suggest the following solution:
$('form').submit(function(e){ //prevent the form from actually submitting. e.preventDefault(); //specify the url you want to post to. //optionally, you could grab the url using $(this).attr('href'); var url = "http://mysite.com/sendPostVarsHere"; //construct an object to send to the server //optionally, you could grab the input values of the form using $(this).serializeArray() var postvars = {}; //call jquery post with callback function $.post(url, postvars, function(response){ //do something with the response console.log(response); }, 'json') });