CPHPython CPHPython - 3 months ago 7
HTML Question

How to copy the state of a manually (un)checked checkbox?

In other words, without triggering Javascript events to change the attributes of the

<input>
, how to preserve the state of a checkbox that I manually checked or unchecked and then copied to another place?

Run the snippet below and check or uncheck a few of them and hit "copy":



$('#cp').click(function(){
$('#copy').html($('#original').html())
$('#copy-clone').html($('#original').clone().html())
})
$('#hi').click(function(){
$('#original input:checked').parent().css('border','2px solid red')
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="original">
<label><input type="checkbox" name="man">man</label>
<label><input type="checkbox" name="woman">woman</label>
<label><input type="checkbox" name="monkey">monkey</label>
<label><input type="checkbox" name="banana" checked="checked">banana</label>
</form>
<button id="cp">copy</button>
<button id="hi">highlight</button>
<br><form id="copy"></form>
<br><form id="copy-clone"></form>





Those previously or manually
:checked
are correctly selected, but the states of the manually changed ones is never copied (run the snippet, select a few, hit "highlight" and then "copy")...

Answer

Use clone(true) to deep copy the element's data/state (docs).

Edit per the Andreas' comment: The html() call on the clone is unnecessary.

$('#cp').click(function(){
  $('#copy').html($('#original').clone())
  $('#copy-clone').html($('#original').clone())
})
$('#hi').click(function(){
  $('#original input:checked').parent().css('border','2px solid red')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="original">
  <label><input type="checkbox" name="man">man</label>
  <label><input type="checkbox" name="woman">woman</label>
  <label><input type="checkbox" name="monkey">monkey</label>
  <label><input type="checkbox" name="banana" checked="checked">banana</label>
</form>
<button id="cp">copy</button>
<button id="hi">highlight</button>
<br><form id="copy"></form>
<br><form id="copy-clone"></form>