$('.search-input').focus(function () {
$(this).val('');
});
$('.search-input').blur(function () {
if ($(this).val() == '') {
$(this).val('enter the place');
}
});
$('#edit-name').keyup(function () {
if ($(this).val() != '') {
$('.username .error-message').remove();
} else {
$('#edit-name').after('<span style="color:red;" class="error-message" >enter the name!</span>');
}
});
$('#edit-name').blur(function () {
if ($(this).val() == '') {
$('.username .error-message').remove();
$('#edit-name').after('<span style="color:red;" class="error-message" >enter the name!</span>');
}
});
$('#edit-pass').keyup(function () {
if ($(this).val() != '') {
$('.password .error-message').remove();
} else {
$('#edit-pass').after('<span style="color:red;" class="error-message"> enter the password!</span>');
}
});
$('#edit-pass').blur(function () {
if ($(this).val() == '') {
$('.password .error-message').remove();
$('#edit-pass').after('<span style="color:red;" class="error-message" >enter the password!</span>');
}
});
Is there a way to merge or beauty the code?thank you.
One of the best functions of jQuery is chaining, in which you can put multiple events with one selector. So you could simply your first two functions like so:
Another option is to put this all under an event-map, like so:
If you have the same function but multiple events, you can actually put bind them all at once by using a
.bindor.on(which is much more preferred) and then adding all the events in one. Then, if you would like to select multiple elements, you can also do so by separating them with commas inside the selector. You can reference the relevant element by using$(this).So you see, you only really need two functions without copying the same thing over and over again.