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

.hide() is not working

Hello everyone, I'm trying to use .hide(), it works for about 0.3s and return to was if before clicked the button.

<form action="#" method="post" name="teste" id="form"> 
    Nome:   <input type="text" name="nome"> <br>
    Email:  <input type="text" name="email"> <br>
    <input type="submit" onclick="validar()">
    </form>
    <p>Tentando funcionar</p>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
        <script type="text/javascript">


    function validar(){
    var nome = teste.nome.value;
    var email = teste.email.value;
    var formulario = teste.value;

    alert("Welcome " + nome + ". Your email is " + email);

    $('#form').hide();


    }

    </script>

2 Answers

Hi Gustavo,

Your code to hide the form is working, what is happening is the default post action of the form is triggering which is causing the page to reload hence why the form appears again. To solve this I would bind an event to the form's submit event using jQuery's event methods and prevent the default action of the form.

<form action="#" method="post" name="teste" id="form"> 
    Nome:   <input type="text" name="nome"> <br>
    Email:  <input type="text" name="email"> <br>
    <input type="submit">
</form>

<p>Tentando funcionar</p>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
    $('#form').on('submit', function(e) {
        e.preventDefault();
        // The above stops the form from triggering, this allows you to remain on the same page

        var nome = teste.nome.value;
        var email = teste.email.value;
        var formulario = teste.value;

        alert("Welcome " + nome + ". Your email is " + email);

        // Hide the form
        $(this).hide();
    });
</script>

Thank you Chris, it's working now. Now I understand, I have to declare some strings before start a function.

Thanks