Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Lewis Turner
Lewis Turner
10,930 Points

Simply jQuery question

I am trying to practice what I have learned. I am trying out some jQuery to add and some html to a page on a button click.

The p tag is added but I don't seem able to remove it, so each time i click the button, It just adds another p tag....

var $invalid = $('<p id=invalid_email">invalid email address!</p>');

$("form button").click(function(){
        event.preventDefault();
        $("#invalid_email").hide()
        $("form").append($invalid);
    }
)

I have tried..

$invalid.hide()
$invalid.remove()
$("form p").hide()
$("form p").remove()

What am I doing wrong? :o(

Lewis

4 Answers

Steven Parker
Steven Parker
215,939 Points

It adds another? I would not expect that since you are adding the same pre-created element. Also, each element you create has the same id, but every id in a document must be unique. You'll need to revise your code to create unique id's to select them later.

Depending on what you're wanting, another idea would be to identify the paragraph to be removed by clicking on it directly. Here's a revised code that will do that, and generate a new p element each time the button is clicked:

$("form button").click(function() {
    event.preventDefault();
    $("form").append($('<p>invalid email address!</p>'));
});

$("form").on("click", "p", function() {
    $(this).remove();
});
Julien riera
Julien riera
14,665 Points

Not to mention, I'm not sure you can hide your element before you appended it.

Lewis Turner
Lewis Turner
10,930 Points

The idea is (I haven't written this code yet) to do validation on some input text to make sure there is an '@', when the button is clicked. If there isn't then display the new p tag. When the button is clicked again, it will remove the existing p tag, do the check again and add the p tag again if there is still no '@' in the input...

Julien riera
Julien riera
14,665 Points

Could "toggle" be an option ?

Another thing, for your tests don't you think making dissapear (toggle/hide/remove) your <p> element when the user clicks in the form would be a better choice so that you're sure you'll be able to notice the changes for sure ?