Sokha
Sokha

Reputation: 3

JQuery : appendTo() within Form element not working

I'm trying to create a page where the text entered by the user in three separate text-areas will be extracted and inserted into a fourth text-area which is generated when a button is clicked. At the moment I'm experimenting a simple version and for some reason cannot generate this additional text-area when the 'Generate' button is clicked. The thing that puzzles me the most is that it works fine if I comment out the <form> and </form> elements!

<!DOCTYPE html>
        <html>
        <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <script  src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><script>
            $(document).ready(function(){
                $("#b1").on("click", function(){
                    $("<div><textarea>come on</textarea></div>").appendTo("#why");
                });
            });
            </script>
        </head>
        <body>
            <form action="">
                <div id="why">
                    <textarea name="IWant">why.</textarea>
                </div>
                <div id="what">
                    <textarea name="IWant">what.</textarea>
                </div>
                <div>
                    <button id="b1" type="submit">Generate</button>
                </div>
            </form>
        </body>
        </html>

Upvotes: 0

Views: 229

Answers (2)

Sudharsan S
Sudharsan S

Reputation: 15393

Use event.preventDefault() in your context. it prevents the default action otherwise your page should be redirected

$("#b1").on("click", function(event){
    event.preventDefault();
    $("<div><textarea>come on</textarea></div>").appendTo("#why");
});

Fiddle

Upvotes: 1

Jamiec
Jamiec

Reputation: 136104

Your submit button will submit the form very quickly after (sucessfully) appending the element. Prevent the form from submiting using preventDefault()

$("#b1").on("click", function(e){
     $("<div><textarea>come on</textarea></div>").appendTo("#why");
     e.preventDefault()
 });

http://jsfiddle.net/pL3L2not/

Upvotes: 0

Related Questions