I am trying to reuse / store an element with all the checkboxes but I'm running into problems using jquery's .clone(). For example:
$('.test1').on('change', ':input', function() {
$temp = $(".test1").clone()[0];
$('#test2').html($temp);
$('#test3').html($temp);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div >
<input type="checkbox" checked> a<br/>
<input type="checkbox" checked> b<br/>
</div>
<div>Test 2</div>
<div id="test2"></div>
<div>Test 3</div>
<div id="test3"></div>
When I make a change to .test1 it should save it to the variable and then take that variable and inset it into test2 and test3. But after it inserts it into test2, it removes it from there and inserts it only into test3.
Is there a work around or a better way to do this while also storing the states?
CodePudding user response:
the issue you are experiencing is likely due to the fact that you are replacing the contents of #test2 with the cloned element and then replacing the contents of #test3 with the same element, which removes it from #test2. You can do this by calling .clone()
$('.test1').on('change', ':input', function() {
var $temp = $(".test1").clone();
$('#test2').html($temp.clone());
$('#test3').html($temp.clone());
});
CodePudding user response:
jQuery is tricking you here, unfortunately. Inside of the html
function, there is a check to see if the value passed is a string. In this case, it is not. The [0]
of your clone is in fact an element.
You can double check this by using jQuery's own check:
console.log(typeof $temp === "string"); //false
As a result, the following code is used:
this.empty().append( value ); // where value is $temp
This means that the first call to .html($temp)
appends the element, and the second call also appends the element. However, it is the same element in this case, and as such it is moved to the final call.
If you want to preserve the state, you will need a clone per insert. Inserting the html of the element will not preserve its checked or unchecked status.
$('.test1').on('change', ':input', function() {
$('#test2').html($(".test1").clone()[0]);
$('#test3').html($(".test1").clone()[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div >
<input type="checkbox" checked> a<br/>
<input type="checkbox" checked> b<br/>
</div>
<div>Test 2</div>
<div id="test2"></div>
<div>Test 3</div>
<div id="test3"></div>