smith
smith

Reputation: 5461

input.length check not working

I try to implement the following code:

<div class="clear"id="usernameline">username:<input type="text" name="username"   id="username" style="border:1px solid #928b8b;"> (at least 3 character)</div>
<div id="usercheck"></div>
<input style="cursor:pointer;border:1px solid #ffffff;background:#c0c0c0;color:#484848" type="button" class="form_button" id="register" value="register!">

<script>
    var error1 = '<span style="color:#ff0000">please fill in your username</span>';
    var error2 = '<span style="color:#ff0000">please insert at least 3 character</span>';
    $("#register").click(function () {
        if ($("#username").val() == '') {
            $("#usercheck").show();
            $("#usercheck").html(error1);
        } else if ($("#username").val() != '') {
            var user = $("#username").val();
            if (user.length <= 3) {

                $("#usercheck").html(error2);

            } else {

                $("#usercheck").hide();
            }
        }
    });       
</script>

When I click register button, if the value length in the input box is larger than 3, $("#usercheck").hide() is not called, can anyone tell me what's wrong in my code, any help will be greatly appreciated.

Upvotes: 0

Views: 133

Answers (1)

Aram Kocharyan
Aram Kocharyan

Reputation: 20431

You need to show again by adding:

$("#usercheck").show();

After if (user.length <= 3) { otherwise it will remain hidden.

EDIT:

I took the time to clean some of the code so the logic is more clear:

<script>
    var error = $("#usercheck");
    var username = $("#username");
    var error1 = '<span style="color:#ff0000">please fill in your username</span>';
    var error2 = '<span style="color:#ff0000">please insert at least 3 character</span>';
    $("#register").click(function () {
        if (username.val() == '') {
            error.show();
            error.html(error1);
        } else if (username.val().length <= 3) {
            error.show();
            error.html(error2);
        } else {
            error.hide();
        }
    });
</script>

Upvotes: 2

Related Questions