What would be the best way to copy input values from one form to another where the inputs in each form have the same name? I came up with the following, however, it seems terribly inefficient (I know, efficiency probably doesn't matter, but would still like to know). Thanks
http://jsbin.com/beyixeqa/1/
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$('#copy').click(function(){
var form1=$('#form1').find(':input');
var form2=$('#form2');
form1.each(function() {
var $t=$(this);
form2.find('[name="'+$t.attr('name')+'"]').val($t.val());
});
});
});
</script>
</head>
<body>
<button id="copy">copy</button>
<form id="form1">
<input name="a" type=text>
<input name="b" type=text>
<input name="c" type=text>
<input name="d" type=text>
</form>
<form id="form2">
<input name="a" type=text>
<input name="b" type=text>
<input name="c" type=text>
<input name="d" type=text>
</form>
</body>
</html>
You don't need to clone or replace, just change the value
jQuery(function( $ ) {
function copyForms( $form1 , $form2 ) {
$(':input[name]', $form2).val(function() {
return $(':input[name=' + this.name + ']', $form1).val();
});
}
$('#copy').on('click', function() {
copyForms( $('#form1') , $('#form2') );
});
});
/*this demo only*/
body{display:flex;}form{padding:16px;background:#ddd;}form>*{box-sizing:border-box;width:100%;}
<form id=form1>
FORM
<input name=a type=text value="FOO">
<input name=b type=button value="BAR">
<textarea name=c>BAZ</textarea>
<select name=d>
<option value="a">a</option>
<option value="b" selected>b</option>
</select>
</form>
<button id="copy">COPY→</button>
<form id=form2>
HIDDEN FORM
<input name=a type=text>
<input name=b type=button value="...">
<textarea name=c></textarea>
<select name=d>
<option value="a">a</option>
<option value="b">b</option>
</select>
</form>
<script src="//code.jquery.com/jquery-3.1.0.min.js"></script>
:input[name]
you're making sure to target only :input
s with a name
attribute$(':input[name]', form2)
= descendants of #form2
val
callback you can target every single one of the targeted inputs:inputs
of #form1
You can use .clone() and .replaceWith()
$('#copy').click(function(){
var newform2=$('#form1').clone(); //Clone form 1
newform2.filter('form').prop('id', 'form2'); //Update formID
$('#form2').replaceWith(newform2);
});
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With