I had a requirement to copy all fields from one form to another similar form. So instead of copying field by field I wrote a routine, form2form, using jQuery.
function form2form(aF1, aF2) {
var selection = "#" + aF1 + " .copy";
$(selection).each(function() {
document.forms[aF2].elements[$(this).attr('name')].value = $(this).val();
});
}
the routine works. The routine requires that in input form field have a class of copy otherwise I don't know how to get all fields in the form. ("#form :input") skips the radio button and select fields.
So my questions are.
Is there a built in function so I didn't need this?
Is there a better way to write the selection?
How do I modify the routine not to need the class.
Can I pass form objects rather then the form name as a text?
Is there a better way in general?
this is a full page that works:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test form2form in jQuery</title>
<script type="text/javascript" src="../scripts/jquery.js"></script></head>
<script type="text/javascript">
function form2form(aF1, aF2) {
var selection = "#" + aF1 + " .copy";
$(selection).each(function() {
document.forms[aF2].elements[$(this).attr('name')].value = $(this).val();
});
}
function testform2form () {
form2form ('form1', 'form2' );
}
</script>
</head>
<body>
<h3>Copy form to form</h3>
<form id="form1" name="form1">
form1: f1 <input type="text" name="f1" id="f1" class="copy" value="from A"/>
f2 <input type="text" name="f2" id="f2" class="copy" value="from B" />
<select name="fruit" id="fruit" class="copy" >
<option value="valApple" selected="selected">Apple</option>
<option value="valOrange">Orange</option>
</select>
</form>
<form id="form2" name="form2">
form1: f1 <input type="text" name="f1" id="f1" class="copy" value="target A" />
f2 <input type="text" name="f2" id="f2" class="copy" value="target B" />
<select name="fruit" id="fruit" class="copy" >
<option value="valApple">Apple</option>
<option value="valOrange" selected="selected">Orange</option>
</select>
</form>
<p><a href="#" onclick="testform2form()">Copy Form to Form (form2form)</a></p>
</body>
</html>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…