-2

I want to add one cell in a section each time I click the add button. The page is updated without refreshing. The html code is:

<section>
  <p class="cell">content</p>
</section>
<button type="button" id="addCell">add</button>

How should I implement the js?Thanks!

Yujun Wu
  • 2,992
  • 11
  • 40
  • 56

3 Answers3

1

Very simple, use append() or after(). In your case append() will work better.

$('#addCell').bind('click',function(){
    $('section').append('<p class="cell">content2</p>');
});

Unfortunately I can't show you a demo because jsFiddle is under maintenance.

Demo in jsbin: http://jsbin.com/agosap/

Nadav S.
  • 2,429
  • 2
  • 24
  • 38
  • fiddle has been excruciatingly slow for me lately so I've switched to [JS Bin](http://jsbin.com). I like it's JS debugger thingy and live updates. – sachleen Jul 12 '12 at 23:04
  • God, thanks for your comment! I've edited my answer and now it contains a dmeo. – Nadav S. Jul 12 '12 at 23:13
0
$(document).ready(function() {
    $("#addCell").click(function() {
         $("section").append('<p class="cell">content</p>');
    });
});
Kijewski
  • 25,517
  • 12
  • 101
  • 143
Chris
  • 4,255
  • 7
  • 42
  • 83
0

I won't give you the code as you haven't shown us what you've attempted, but I will guide you.

You want to bind a click event to the button so you can do stuff when the user clicks it. You can create elements using JS document.createElement or using jQuery. So inside the click event, create the element you want, give it whatever attributes you want, and then append it to the parent div.

Community
  • 1
  • 1
sachleen
  • 30,730
  • 8
  • 78
  • 73