Please help a jQuery newby with the following. I have a form and I’m trying to add successive chunks of form fields when an #addMore button is clicked. With the help of this board, I have that working now. But it only works once. I’ve whittled things down to a minimal case:
<html>
<head>
<title>Reserves Form</title>
<script src="../jquery/jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function() {
var chunk = $('.content').clone(true);
$('#addMore').live('click', function() {
alert('debug!');
$('#container').append(chunk);
});
});
</script>
<body>
<div id="container">
<p class="content">lorem ipsum blah blah</p>
</div>
<button type="button" id="addMore">Add Another Paragraph</button>
</body>
</html>
When I load the page and click the button, I see the debugging alert and then a clone of the “content” paragraph appears as expected. When I click the button again, I get the alert, but not the new paragraph. Why would one response to the click work, but not the other? And how can I get them both to work?
You are appending the same object again and again to the same container so you won’t see any difference as if it is not doing anything.
Try this which will clone the first
.contentelement inside the click handler and append it.Alternatively you can try this which will append html string instead of cloned object. In this approach the clone is used only once because string appending can be done any number of times so it is better than previous approach.