Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
229,732 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 ?