[SalesForce] How to get the Id from the standard pop up window

I have a page with Contact look up icon and when clicked on it shows up the standard salesforce lookup pop up window.

When this happens, I see that the below fields are auto-generated:

<input type="hidden" name="j_id0:j_id49:contFieldId_lkid" id="j_id0:j_id49:contFieldId_lkid" value="003j000000APTqv">

When user selects the record in the popup window, the field is set to the new Id..My question is how do i get the value of this using javascript.

I tried adding a change event for this but this is a hidden element and changed by salesforce, So I am not able to intercept the event..

j$('input[id$=contFieldId_lkid]', 'change', function(n) {
  alert('Value changed'); //but this never gets called.
});

Any help on this?

Note: There are articles online on how to do the custom popup window but my case is different as I am using the standard salesforce popup window.

Best Answer

It's not best practice to interfer with this salesforce internal markup. Reason is that for all this you risk that salesforce updates might break your code.

This caveat emptor expressed I actually like to play with internals and changes in VF/markup where rare in the last years. With focus on lightning they might become even rarer.

Your problem could be that you're attaching the event too early (e.g. in $(document).ready) and the hidden fields simply don't exist at that time.

You could attach handler on somthing existent and try to trace the event until they finally reach the hidden fields. Or create a timer with setInterval looking for fresh created hidden fiels. Or reverse engineer the sfdc.js and even extend/override some of it's methods. I've done this for crazy things but can't recommend it for your use case. Simply because it's more effort and you'll end up with a more fragile result.

So better clamp teeth and go for the custom picker where you control everything. To loose the standard picker isn't too sad: take the chance and improve the user experience e.g. by autocompletes as you type, better searching capabilities or better doublette handling.