user1002039
user1002039

Reputation: 860

JQuery Hiding Prepend Elements

I can't figure out how to hide prepend span tags. I have the following JQuery code that prepends span tags as error messages in a form:

$('.mcEmail').each(function() {
        var mcEmailCheck = $(this).val();
        var mcEmailRegex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

        if(!mcEmailCheck.match(mcEmailRegex)) {
            mcResponse('- Incorrect Email format!', true);
            $(this).parent().prepend('<span class="mcCustResponse">- Incorrect Email format!</span>');
            $(this).addClass('mcError').fadeOut().fadeIn();
        }
    });

Then I try the following:

$('.mcCustResponse').click(function(){
    $(this).fadeOut(1000);
});

The same is used for all other validation. The error messages show up fine. I can pretty much try anything on these span tags and nothing works. Can't hide, fade out, remove etc. What am I doing wrong?

Thank you!

Upvotes: 0

Views: 317

Answers (3)

Aram Mkrtchyan
Aram Mkrtchyan

Reputation: 2700

$('.mcCustResponse').live("click", function(){
    $(this).fadeOut(1000);
});

or

$('.mcCustResponse').bind("click", function(){
    $(this).fadeOut(1000);
});

Upvotes: 1

Brian Glaz
Brian Glaz

Reputation: 15686

Which version of jquery are you using? You need to use .live() or .on() depending on the version. The problem is that your spans with class mcCustResponse don't exist when the page loads. The code block you have with .click() will only register events for the elements on the page at load time. You can make a function that will register events to all elements with class mcCustResponse now and in the future using .live() or .on().

http://api.jquery.com/on/ - .on() jquery 1.7

http://api.jquery.com/live/ - .live() before 1.7

Upvotes: 1

Chris Kempen
Chris Kempen

Reputation: 9661

What about creating the span first, then adding and manipulating it after:

var span = '<span class="mcCustResponse">- Incorrect Email format!</span>';
span.hide();
$(this).parent().prepend(span);

...

$(this).parent().find('span').show();

Hope this helps! :)

Upvotes: 0

Related Questions