marziobs
marziobs

Reputation: 61

jQuery hide() does not hide parent

JQuery still driving me mad... Here's the problem: I have a page where visitors can leave their email address by clicking on a link inside a div (id="contact").

<div id="contact"><a href="">vuoi lasciare un recapito?</a></div>

Once clicked, the "contact" div loads a php form. The user types in his email address, then the address is checked, then inserted in the Database, etc... Usual business.

$(document).ready(function() {
$('#contact a').click(function()
    {
    $('#contact').load('mailform.php');
    return false;
    });
$('#contact').submit(function(){
    var email = $('input[name=email]', '#submitmail').val();
    var submit = $('input[name=submit]', '#submitmail').val();
    $('#contact').load('mailform.php',{'email': email,'submit': submit});
    return false;
    });
//the close button - start
$(".cls").click(function(){
    alert($(this).parent().html());
    $(this).parent().hide();
    });
//the close button - end
});

The pain comes when I want to add a "close" button or link, so the user can hide the form after or even before filling the form.

<div id="submitmail">
    <form action="#" method="post">
        <fieldset>
        <p><label for="email"><?php echo $_SESSION['nome']; ?></label><input type="text" name="email" /></p>
        <p class="submit"><input type="submit" name="submit" value="inserisci" /></p>
        </fieldset>
        </form>
</div>
<span class="cls">Chiudi</span>

The link (and the "the close button" script) simply don't work. No alerts, no switches, no div disappearing... Nothing. Already tried $('span.cls').click(function() and $('#cls').click(function() (after switching the "span" with a "div" and the class with an ID) no clues. Just a link to click that does nothing. Firebug and IE dev toolbar don't even get into the function. Alternative solutions are welcome...

Thank you!

Upvotes: 1

Views: 1022

Answers (3)

karim79
karim79

Reputation: 342635

Try this:

$("#contact").on("click", ".cls", function(){
    alert($(this).parent().html());
    $(this).parent().hide();
});

since the .cls element does not exists at the time of binding - so you need to delegate the handler to a suitable parent element. Read the "direct and delegated events" section of this:

http://api.jquery.com/on/

Excerpt from above link:

If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler...

Upvotes: 4

roncsak
roncsak

Reputation: 618

You did not copied here the parent of the following html:

<span class="cls">Chiudi</span>

Try this:

$(".cls").click(function(){
    // alert($(this).parent().html());
    $('#submitmail').hide();
});

Upvotes: 0

MassivePenguin
MassivePenguin

Reputation: 3711

My guess is that the close button is not part of the DOM on documentReady.

Upvotes: 0

Related Questions