开发者

Using return true or return false on a link with target blank in jQuery

I have a form that has target="_blank"on submit.

I want to validate the form however, prior to it launching the new window. I could use window.open instead, but then it can be blocked by popup blockers.

The problem I'm having is the validation uses ajax and the time it takes to get the response for return fals开发者_如何学Goe, is too long and it opens the new window.

 $('.submit').click(function(){
        $.post("/ajax/save/", { state: $('.state_field').val() },
            function(data) {
                if(data == 'false'){
                    alert('invalid state');
                                    return false;
                }else{

                    return true;
                }
            }
        );
  });

Would anyone have suggestions as how I can workaround this?

Thank you!


(You should probably use $("form").submit(function() {}) because that also catches when somebody presses Enter in a textfield.)

What you could do is

  1. Don't include the target="_blank" in the form
  2. catch the submission and block it (preferably using event.preventDefault();)
  3. do the ajax call for validation
  4. from within the callback: add the target="_blank" and submit the form again (you could use a check like $("form[target]").length == 1 to see if the form is being submitted for the second time.

While this all can make it work, you should think about validating the form right after the user enters data in each field, this will also improve the user experience a lot.


Use the preventDefault method of the event at the beginning of your click.

$('.submit').click(function(event){
event.preventDefault();
[...]

This will stop your form from submitting and is a better solution than using return false;.

If you need to do a redirect after the ajax call you can do that the standard way:

window.location.replace([url to redirect to]);


Popup blockers block the new window if they are opened in script execution context. If the window is opened through user action then it is allowed. You can try to use jQuery ajax in synchronous mode this will solve your other part of the question because the function will not wait untill ajax response comes and you return true/false conditionally.

       $('.submit').click(function(){
            $.ajax({
              url:  "/ajax/save/", 
              type: "POST",
              async: false,
              data: { state: $('.state_field').val() },
              success: function(data) {
                    if(data == 'false'){
                        alert('invalid state');
                        return false;
                    }else{

                        return true;
                    }
                }
            );
      });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜