简体   繁体   中英

Get the id of element focus is moving to in jQuery.blur event?

I've written some code using jQuery to do an ajax call and display a message on the page when the user moves focus away from a field. My field is called txtLogin and the user types in some text and clicks a button to create a new user account in a database using the given txtLogin value.

The issue is that a valid value must contain four letters, a dash, and then four more letters. My client insists that the form should have two fields, one for the first four letters, and another for the second four letters.

Suppose that these two fields are called txtLogin0 and txtLogin1 . I still want to do an ajax call when the user moves focus away from the field, but the ajax call should not be invoked when the user moves from one of the two fields to the other!

My current code looks like this.

$('#txtLogin').blur(function() {
    var login = $(this).val();
    var isValid = testLogin(login);
    if (!isValid) alert('Login is invalid');
});

I imagine my new code looking like this:

$('#txtLogin0').add('#txtLogin1').blur(function() {
    var focusId = The Id of the newly focused element
    if (focusId==='txtLogin0' || focusId==='txtLogin1) return
    var login = $(#txtLogin0').val() + '-' + $('#txtLogin1').val();
    var isValid = testLogin(login);
    if (!isValid) alert('Login is invalid');
});

How can I get the id of the element that the focus moves to in the jQuery.blur event?

A simple hack is to create two var to store the current and previous element in onfocus and onblur and call the validate method inside a timer which will be triggered in 0 milli seconds.. Try below code and I think it is close to what you want.

DEMO

var prevEl, curEl;
$(document).ready(function() {
    $('#txtLogin0, #txtLogin1').blur(function() {
        prevEl = this.id;

        setTimeout(validateLogin, 0);

    }).focus(function() {
        curEl = this.id;
    });
});

function validateLogin() {
    if ((prevEl === 'txtLogin0' && curEl === 'txtLogin1') || (curEl === 'txtLogin0' && prevEl === 'txtLogin1')) {
        return;
    }
    prevEl = ''; curEl = '';
    var login = $('#txtLogin0').val() + '-' + $('#txtLogin1').val();
    var isValid = testLogin(login);
    if (!isValid) alert('Login is invalid');
}

function testLogin(txt) {
    return false;
}
var focusId = $(this).attr('id');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM