3
votes

I've got a simple login form with email and password I have this code to validate the email

$(document).ready(function() {

$('#login-submit').click(function() {

    $(".error").hide();
    var hasError = false;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

    var emailaddressVal = $(".email").val();
    if(emailaddressVal == '') {
        $(".email").after('<span class="error">Please enter your email address.</span>');
        hasError = true;
    }

    else if(!emailReg.test(emailaddressVal)) {
        $(".email").after('<span class="error">Enter a valid email address.</span>');
        hasError = true;
    }

    if(hasError == true) { return false; }

    });
});

the span with the class of .error (as per the design I've got) hides the input element.

I want to hide the error message again when I click it

$(document).ready(function() {
$('.error').click(function() {
    $(".error").remove();
});

});

but this does nothing. Anyone know what I'm doing wrong here?

2

2 Answers

2
votes

Problem

Currently, you are binding the click handler to any .error element that exists on page load. But your .error messages are added to the DOM dynamically after page load, so your click handler is not bound to them.

Solution

Instead of directly binding the event handler to the elements, you should delegate the event handler higher up the DOM to a parent element that exists on page load.

For example:

$(document).ready(function() {
    $(document).on('click','.error', function() {
        $(this).remove();
    });
});

This will have the click handler apply to any .error element included in the DOM, both current and future. You can of course limit the scope of delegation, by attaching it for example to $('#some-form') instead of $(document).

0
votes

You might want to try Bootstrap alert messages. They're really simple to use, and work within your page really simply, as they come with their own close buttons. You can treat them as you would treat any other DOM element, but without the hassle. All you have to do is install their library and use their classes/javascript in order to get what you want. It takes a bit of getting used to, but it's an incredibly powerful addition.

http://twitter.github.com/bootstrap/components.html#alerts