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

Checking if every specific item in list is in hashmap?

java python arrays hashmap jython

I'm bukkit jython/python plugin coder, but I'm stuck here. I have an array.array (so ArrayList) which is pregenerated by server, and returns list of online players.

SQL Server 2005: T-SQL to temporarily disable a trigger

sql-server sql-server-2005 tsql

Is it possible to disable a trigger for a batch of commands and then enable it when the batch is done?