Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  132] [ 1]  / answers: 1 / hits: 17356  / 11 Years ago, wed, january 15, 2014, 12:00:00

The below code is for repeating a div. But it does not work. Please help me.



<html>
<head>
<script>
$(.repeat).live('click', function () {
var $self = $(this);
$self.after($self.parent().clone());
$self.remove();
});
</script>
</head>
<body>
<form>
<div class=repeatable>
<table border=1>
<tr><td><input type=text name=userInput[]></td></tr></table>
<button class=repeat>Add Another</button>
</div>
<input type=submit value=Submit>
</form>
</body>
</html>

More From » jquery

 Answers
12

First add jquery in your code and use on() in place of live().



Also write your code in $(function(){...}) so, that your code will work after document ready



<script src=http:/code.jquery.com/jquery-1.9.1.js></script>
<script>
$(function () {
$(.repeat).on('click', function () {
var $self = $(this);
$self.after($self.parent().clone());
$self.remove();
});
});
</script>


Working Demo



Updated, if you want it to work for more inputs then try this,



$(function () {
$(.repeat).on('click', function (e) {
e.preventDefault();// to prevent form submit
var $self = $(this);
$self.before($self.prev('table').clone());// use prev() not parent()
//$self.remove();// remove this line so you can add more inputs
});
});


Updated Demo


[#73157] Tuesday, January 14, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayla

Total Points: 681
Total Questions: 102
Total Answers: 108

Location: Marshall Islands
Member since Tue, Sep 21, 2021
3 Years ago
tayla questions
Fri, Mar 5, 21, 00:00, 3 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Thu, Apr 9, 20, 00:00, 4 Years ago
;