[SalesForce] How to use jQuery to get the id of a lookup field when the field is changed

I am using jQuery to try to get the id of a lookup field (Account_Contact__c) when the user selects a different value. Here is my code:

var j$ = jQuery.noConflict();   

function handleResult(result, event) {
    j$('[id$="Account_Contact_Email__c"]').val(result); 
}

j$(document).ready(function(){
    j$(document).on('change', '[id$="Account_Contact__c"]', function() {
        var newAccountContactId = j$('[id$="Account_Contact__c_lkid"]').val();
        console.log(newAccountContactId);  //this is returning an empty string
        myVFPageController.myMethod(newAccountContactId, handleResult);
    });
})

The problem I'm facing is that newAccountContactId keeps coming up empty, even when there's a value in there. However, if I run j$('[id$="Account_Contact__c_lkid"]').val() in the console in Firefox, it returns the correct value.

Any thoughts on what I'm doing wrong?

Best Answer

The lookup Id is not populated the exact time the value of the lookup is changed. So I suggest you add a small timeout after the change and then check for the value. Try something like this:

j$(document).on('change', '[id$="Account_Contact__c"]', function() {
    //add a 200 milisecond timeout
    setTimeout(function(){
        var newAccountContactId = j$('[id$="Account_Contact__c_lkid"]').val();
        console.log(newAccountContactId);  //this is returning an empty string
        myVFPageController.myMethod(newAccountContactId, handleResult);
    },200);
});
Related Topic