onsubmit refresh html form

2019-02-17 04:06发布

I'm trying to use Javascript to submit the form's data. Here's 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 issue is that the Javascript runs but the form still processes and refreshes the page..

I put the return false; code in hoping it would stop the form from refreshing.

5条回答
爷、活的狠高调
2楼-- · 2019-02-17 04:48

Since you added the jQuery tag, this it the best way to do this:
unobtrusive event attach

$('form').submit(function(){
        alert('the form was submitted');
        return false;
    });

In your's way it should be;

<form onsubmit="return post();">
查看更多
贪生不怕死
3楼-- · 2019-02-17 05:01

You will have to put the return false part after the post() function in the onsubmit handler, like so:

<form onsubmit="post();return false;">
//input fields here
</form>
查看更多
放荡不羁爱自由
4楼-- · 2019-02-17 05:01

Keep your 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();
});
查看更多
forever°为你锁心
5楼-- · 2019-02-17 05:09

You need to actually return false from your inline dom-0 handler. So change

onsubmit = "post();">

to

onsubmit = "return post();">

Or you could give your form an id and do this:

<form id="form1" onsubmit = "post();">

Then from a safe location in which your dom is ready:

document.getElementById("form1").onsubmit = post;
查看更多
在下西门庆
6楼-- · 2019-02-17 05:09

Since this post is tagged with jQuery, I'll offer 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')
});
查看更多
登录 后发表回答