Search code examples
javascriptdom-eventsonblur

Issues with using onBlur event


I have taken a look around Stack Overflow on the topic of onblur but so far have not been able to locate an approach to solve what I want to do.

What I have is a simple two column tables with an unknown number of rows. Rows are created at render time based on the number of boxes being shipped. Each column has the following name and id for the input box:

For column 1: shipItems[ rowNum ].barcode
For column 2: shipItems[ rowNum ].trackingcode

Pretty straight forward. What I want to do is validate the trackingcode and if in error alert the user and re-focus the cursor on the column/row that caused the problem. Users will be using a scanner to scan in the information.

Every things works except that I can not get the cursor to go back to the column/input that caused the issue in the onBlur event.

My understanding is that when the onBlur event fires the element is losing focus and thus the focus is being transferred to the new/next element.

I have tried to playing around with the onfocus event, onkeypress events but still have not been successful.

I am open to any ideal to get this done, I have spend way to much time on it as it is. JQuery is not out of the questions or just plan old Javascript.


UPDATE

Here is a link to the script on jsFiddle:


Solution

  • After reviewing your code, best I can tell you are experiencing an unusual bug in jQuery. I have seen some quirky things happen when using focus() (like having to use setTimeout). But, in your case the $(this) is somehow not resolving correctly when calling focus().

    At first I thought it was because the id is not following HTML-4 standards, but correcting the id did not help. $(this) still failed to focus, despite the fact it correctly refers to the <input> element. Then I tried identifying the id with jQuery as a string $("'#" + thisId + "'")...still did not work. But, a hard coded id did work...

    So, here's how I modified your code and worked around the problem to get it to focus

    if( null === $text.match(/\b(1Z ?[0-9A-Z]{3} ?[0-9A-Z]{3} ?[0-9A-Z]{2} ?[0-9A-Z]{4} ?[0-9A-Z]{3} ?[0-9A-Z]|[\dT]\d\d\d ?\d\d\d\d ?\d\d\d)\b/))
    {
        alert("No Match");    
        //$(this).focus();//don't use jquery $this
        var thisId = $(this).attr('id');//get the id
        //use the setTimeout workaround for firefox
        setTimeout(function() {
          document.getElementById(thisId).focus();//use javascript to set focus
        },0);
        $(this).css('background-color','Red');
    }
    

    Feel free to look at the fiddle (linked above). This approach does correct the focus problem.