Tutorial :Append to a div using jquery



Question:

I'm trying to add content to a div every time a link is clicked. However, the added text dissapears immediately after being added. What am I doing wrong?

 <html>                                                                     <head>                                                                     <script type="text/javascript" src="/files/jquery.js"></script>             <script type="text/javascript">                                                $(document).ready(function() {        $("a").click(function() {        $("#questions").prepend("A question<br />");         });     });    </script>                                                                 </head>                                                                   <body>                                                                     <a href="">Add</a>     <p id = "questions"> </div>     </body>                                                                      </html>  


Solution:1

Add return false; to your click-event, to prevent it from reloading the page.


Solution:2

<a href="#">Add</a>

You need to have something in your "href", else it'll go navigate to the same page (at least for Firefox).


Solution:3

I agree with O.K.W

also putting return false; or passing through a variable to represent the control on the function and performing preventDefault will stop the natural click event.

function(e){  e.preventDefault();  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »