Any way to override .blur() if .submit() is called upon in jQuery?

那年仲夏 提交于 2019-12-12 16:18:07

问题


I'm writing up custom code for a CMS for a website. When a user clicks on the submit button (created with jQuery UI), it calls the click event on the button, which in turn calls a submit event, which submits the form.

Said form also checks specific fields to see if they have text, and will show error messages and deactivate the submit button until the issues are resolved. To do this, I currently use .focus(), which has a .blur() function inside it which checks to see if the error was fixed and removes the notice if so (and if there's no other errors, re-activates the button).

Now, the issue I have is that if the user edits one of the fields being checked at any time, if they don't click out of it and try submitting the form data, the .blur() function takes control (as it should by how this is coded), so it takes a second click to submit the form data.

Is there a way to have .submit() take precedence over .blur() in jQuery so this issue can't occur (for now I can simply tell the users using this to not do the steps to cause it)?

(If you guys need code I can try posting some bits of it in here.)


回答1:


Try stopping the event propagation of the onblur event:

$(form).submit(function(){
  blur.stopPropagation()
...
});

See here: http://api.jquery.com/event.stopPropagation/




回答2:


I tried removing the blur event on the input fields and making use of onFocusout event of form validate function. That solution worked for me.

Other Best soluton is to set timer that delays the blur event action before it fires the button click event.

// Namespace for timer var setTimer = { timer: null }

        $('input,select').blur(function () {
            setTimer.timer = setTimeout(function () {
               functionCall();
            }, 1000);
        });

        $('input,select').focus(function () {
            setTimer.timer = setTimeout(function () {
                functionCall();
            }, 1000);
        });

        $("#btn").click(function () {
            clearTimeout(setTimer.timer);
            functionCall();
        });   



回答3:


After thinking about it a bit last night I realized that if I did a quick check to make sure if the error was visible or not before I called blur(), it would fix my problem (did a quick test and it seems to have).

Thanks for the suggestion about the event propagation stop, though, I'll have to keep that in mind.



来源:https://stackoverflow.com/questions/3349882/any-way-to-override-blur-if-submit-is-called-upon-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!