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 ther开发者_开发百科e should be something similar.
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" : "");
});
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.
精彩评论