javascript - How to copy the state of a manually (un)checked checkbox? -
in other words, without triggering javascript events change attributes of <input>
, how preserve state of checkbox manually checked or unchecked , copied place?
run snippet below , check or uncheck few of them , 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 or manually :checked
correctly selected, states of manually changed ones never copied (run snippet, select few, hit "highlight" , "copy")...
use clone(true)
deep copy element's data/state (docs).
edit per andreas' comment: html()
call on clone 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>
Comments
Post a Comment