开发者

AJAX form submission when enter is used to submit

I have a designer insisting on a single form field submitted by hitting enter and the post made by AJAX and the response presented by Fancybox.

Problem is the the return false is not preventing the submission of the page.

What am I doing wrong there?

<form id="home_stay_informed_form">
<input name="informed_email" id="home_informed_email" value="Enter your email address..." />
</form>


$('#home_stay_informed_form').submit(function() {
  var reg = new RegExp(/^\S+@\S+\.\S+$/);
  var em = $("#home_informed_email").val();
  if (!reg.test(em)) {
  alert('Please correct your email address.');
  $("#home_informed_email").focus();
    return false;
  } else {
  $.ajax({
    type: "POST",
    url: 'listSubscribe.php',
    data : 'email=' + em,
    success: function(msg) {
     $("#home_stay_informed_form_msg").fancybox({
    'titlePosition'  : 'outside',
    'transitionIn'  : 'none',
    'transitionOut'  : 'none'
   });
    $("#home_informed开发者_运维知识库_email").val('Enter your email address...');
    return false;
    }
  });   
  }
});


The return false needs to do in the submit handler directly, like this:

$('#home_stay_informed_form').submit(function() {
  var reg = new RegExp(/^\S+@\S+\.\S+$/);
  var em = $("#home_informed_email").val();
  if (!reg.test(em)) {
    alert('Please correct your email address.');
    $("#home_informed_email").focus();
  } else {
    $.ajax({
      type: "POST",
      url: 'listSubscribe.php',
      data : 'email=' + em,
      success: function(msg) {
        $("#home_stay_informed_form_msg").fancybox({
          'titlePosition'  : 'outside',
          'transitionIn'  : 'none',
          'transitionOut'  : 'none'
        });
        $("#home_informed_email").val('Enter your email address...');
      }
    });   
  }
  return false;
});

Your success handler doesn't run until the server response comes back, so your function is actually returning undefined for that else statement...and that return false inside doesn't have any effect. Putting it in the submit handler directly like is it above will do what you want, preventing the form submit.


A bit cleaner would be event.preventDefault(), by adding the event parameter here:

$('#home_stay_informed_form').submit(function(e) {

And replacing return false with

e.preventDefault();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜