Reputation: 8170
This is my simple html page :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="jquery.min.js"></script>
<script >
function copy(){
$("#two").html($("#one").html());
}
</script>
</head>
<body>
<button onclick="copy()">copy</button>
<div id="one">
<input type="checkbox" name="test" >
</div>
<div id="two">
</div>
</body>
</html>
when I click the button, contents of div#one
is copied to div#two
, but when I first click on checkbox (It is checked now!) and then click the Button, The second checkbox is produced, but it is not checked!! why?
Upvotes: 0
Views: 537
Reputation: 2189
You can also use jQuery .clone()
method, which will avoid the .is(':checked')
verification. Instead of using .html()
replace your code to below:
$('#two').html($("#one").clone());
Alternate method:
You can also first check and see if the first checkbox is checked using jQuery.
// verify if first checkbox is checked
if ($('#one input[type="checkbox"]').is(':checked')) {
// add checked attribute to second checkbox
$('#two input[type="checkbox"]').prop("checked", true);
}
Have a look at the code below.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="jquery.min.js"></script>
<script >
function copy(){
$('#two').html($("#one").clone());
}
</script>
</head>
<body>
<button onclick="copy()">copy</button>
<div id="one">
<input type="checkbox" name="test" >
</div>
<div id="two">
</div>
</body>
</html>
Upvotes: 1
Reputation: 1545
.html() do not copy all the elements with their attributes. So you just use this line -
$("#one").clone().appendTo("#two");
Upvotes: 1
Reputation: 5081
Using .html()
only copies the plain HTML code of the target element, not other data like whether or not boxes are checked. If you want to include such data, use .clone()
instead.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="jquery.min.js"></script>
<script >
function copy(){
$("#two").html($("#one").clone());
}
</script>
</head>
<body>
<button onclick="copy()">copy</button>
<div id="one">
<input type="checkbox" name="test" >
</div>
<div id="two">
</div>
</body>
</html>
This will work for any number of checkboxes, as well as data for other elements such as a textbox's value.
Upvotes: 3