Blur jQuery and submit distribution issue

I have a simple new user form with a Display Name field that fires an ajax call on a blur () event. This is to check if an entered value already exists in the database.

Example:

$("#displayname").blur(function() { //do something }) 

After specifying the display name, the user clicks the "Submit" button to continue further, which is the next immediate action on the form.

Example:

 $("#button").click(function() { $("#form").trigger("submit"); }) 

However, the blur () event is ALWAYS fired first and the button is not logged. It is only at the second press of a button that the spread becomes correct. It causes chaos in my form.

Is there a way to disable the blur () event of a text box WHEN I click a button?

Thanks for any help ur!

+4
source share
2 answers

If I understand you correctly, the problem occurs when blur caused by a button click.

Fortunately, event information is passed to the handler, and the event must contain the target property. From this, you can conclude that there is something to do with blur . Use your favorite js debugger to stop in the blur event handler and see what is from the target property.

 $("#displayname").blur(function(evt) { if (evt.target is not the button){ // figure this out with debugger //do something return true; // I handled it } return false; // I didn't handle it }) 

However, in this case, you will not perform your dynamic check that everything in the field is missing from the database.

@eZakto has a good suggestion to disable the submit button until an ajax check is done on your input.

+3
source

You are looking for "event.relatedTarget". For focusOut or blur events, this is set to the element receiving the focus, so you know that the blur is caused by pressing the submit button, and not by any other event.

 $("#displayname").blur(function(event) { if (event.relatedTarget && (event.relatedTarget.id === 'button')){ $("#button").trigger('click'); } else { // do blur stuff here } }); 
0
source

Source: https://habr.com/ru/post/1380574/


All Articles