1

I have problem with login validation using javascript. When the user doesn't provide any username or password the pop up message is showing please enter the username and password. I want that when user doesn't provide username the pop up message will come please enter the username, then if i press OK button cursor should go in txtusername textbox. In case of password also same thing should happen, cursor should go in txtpassword textbox. But in my programming the pop up message is coming but after pressing ok button cursor is not placing in expected position, please somebody modify my code. Here is my code.

<script type="text/javascript">
    //Function to check valid login
    function validLogin() {
        if (document.getElementById("TxtName").value == "") {
         alert("Please enter your UserName");
         return false;             
        }
        if (document.getElementById("Txtpassword").value == "") {
           alert("Please enter your Password");
         return false;
        }
        return true;
    }

<asp:Button ID="BtnLogin" runat="server" Text="Login" onclick="BtnLogin_Click" OnClientClick="validLogin()"/>

2 Answers 2

4

Give this a try (assuming you meant TxtName, as in your code, not TxtUsername, as in your question.

<script type="text/javascript">
    //Function to check valid login
    function validLogin() {
        var name = document.getElementById("TxtName");
        if (name.value == "") {
           alert("Please enter your UserName");
           name.focus();
           return false;             
        }
        var password = document.getElementById("Txtpassword");
        if (password.value == "") {
           alert("Please enter your Password");
           password.focus();
           return false;
        }
        return true;
    }
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

I think you also want to trim whitespace from the values. function trim(s){return s.replace(/^\s\s*/, '').replace(/\s\s*$/, '');} // blog.stevenlevithan.com/archives/faster-trim-javascript
0

use element.focus() after your alert. i.e.

alert("please enter your UserName");
document.getElementById("UserName").focus();

Comments

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.