views:

43

answers:

2

I am trying to write a script that validates user input. Like: letter length more than 5 or password and reentered-password match. But how can I get which input box in the form was clicked? I used

$(function() {
    $('#register input').keyup(function() {
        if ($('#username').val().length < 5) {
            $('a.username').text("Please fill");
        } else {
            $('a.username').text("");
        }

        if ($('#password').val().length < 5) {
            $('a.password').text("asdasd");
        } else {
            $('a.password').text("");
        }

    });
});​

And

New User User Name

        <label for="password">Password</label> <input type="password" id="password" name="password"><a class="password"></a>

    </fieldset>
</form>

When I click one of input elements, the code runs and it sees that second password input is also not full field and second <a> tag also fires. Should I use several .keyup functions for each element, or is there any method for getting which element clicked? Like

if (clicked == $("input#username") && $('#username').val().length < 5) {
    $('a.username').text("Please fill");

} else {
    $('a.username').text("Please fill");

}​

but this does not work. I think there should be something similar.

A: 

As a general rule, you should use specific event binding if you want to get specific events, rather than getting them all and doing your own filtering. (If you wanted to do it the other way, you'd want to look at either this, $(this) or the event, depending.)

However, for form validation, there's already code to do that. For example, the jQuery Validation plugin for general form validation, and an extension specifically for passwords. In your shoes, I'd at least start with one of those rather than building things from scratch.

William Pietri
+1  A: 

You can use $(this) inside the handler to refer to the element the keyup event occurred on. Also, you can use .next() to move from it to the <a> you're setting the text of, like this:

$('#register input').keyup(function(){
  $(this).next().text($(this).val().length < 5 ? "Please fill" : "");
});
Nick Craver
but how can I understand that is $(this) object is password field?For example I want to check that password and re-password fields are same.
Meko
@Meko - You can check the id with `this.id` or bind a handler *just* for that input, for example use `$("#repassword").keyup(...)` instead, then the handler will *only* run on that event, and `this` will always be `#repassword`.
Nick Craver