Set focus on the same control where validation fails on blur event, JQuery

I have a form that has dynamic controls created using jQuery. I have applied validations on the controls using jQuery. I am validating the controls on blur event. The problem here is that i need to set the focus on the same control where validation fails on blur event.

I have done something like this:

$(propVal1).blur(function () {
    if(!ValidateNumber(this, propName1)) {
        alert('Value should be numeric in ' + propName1);
        setTimeout(function() {$(this).focus();}, 1);
    }
});

Where propVal1 represent an input control created dynamically, propName1 is the string name of the property.

Answers


The reason this is happening is that your input control is the only control in the window, so after it loses focus the whole window loses focus and you can't focus an input in a window that doesn't have the focus.

This is the test html I made to confirm this:

<form>
    <input id="my_input" type="text" />
    <input id="my_input2" type="text" />
</form>

<script type="text/javascript">
    $("#my_input").blur( function () { alert('bad input'); setTimeout( function() { $(window).focus(); $("#my_input").focus() }, 1 ); return false }  );
</script>

If you comment out the second input the code will not work!

One possible solution is to have an invisible input after your input to catch the focus when the first one blurs.


Need Your Help

How do you get the values of their textboxes and transfer them to richtextbox?

c# .net winforms textbox richtextbox

How do you get the values of their textboxes and transfer them to richtextbox?

Android: Pause/Resume Timer OR Thread

java android multithreading timer

I have checked all SO answers about how to pause/resume timer, but can't find a solution.