1

In a textbox user can enter date. In OnChange event I am trying to validate the date using javascript, if it is not a valid date showing an alert message and setting the focus on the textbox.

Here when I enter invalid date and press tab, the onchange events fires , in case of invalid date it does not set focus on the texbox, instead the focus is set on next textbox in the form.

<asp:TextBox ID="txtDateOfBirth" runat="server"
    onchange="validateDate(this)"></asp:TextBox>

function validateDate(sender) {
    if (!Date.parseInvariant(sender.value, "MM/dd/yyyy")) {
        alert("date is incorrect");
        sender.focus();
    }
}
3
  • You should be able to solve this with a little debugging... Commented Mar 28, 2012 at 16:00
  • sender.focus() and $(sender).focus() are same. Commented Mar 28, 2012 at 16:05
  • What's likely happening is that the tab keypress event is being processed after the onchange event, so the focus is indeed set to the textbox, but it was already there, and then the keypress event occurs moving focus to the next textbox. Commented Mar 28, 2012 at 16:29

1 Answer 1

1

Try using onblur instead of onchange:

<script type="text/javascript">
    check = function (sender) {
        if (sender) {
            alert("check");             
            sender.focus();
        }
    }
</script>
<asp:TextBox ID="txtTest" runat="server" onblur="check(this);"></asp:TextBox>

In the above example, focus is returned to the input as expected.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks James!!! meanwhile I found a workaround , set focus on some other control and then set focus on the current control. e.g $(input).focus(); sender.focus(); It worked for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.