【发布时间】:2009-09-16 22:29:31
【问题描述】:
我需要将所有字段从一个表单复制到另一个类似的表单。因此,我没有逐个字段地复制,而是使用 jQuery 编写了一个例程 form2form。
function form2form(aF1, aF2) {
var selection = "#" + aF1 + " .copy";
$(selection).each(function() {
document.forms[aF2].elements[$(this).attr('name')].value = $(this).val();
});
}
例程有效。该例程要求在输入表单字段中有一类副本,否则我不知道如何获取表单中的所有字段。 ("#form :input") 跳过单选按钮并选择字段。
所以我的问题是。
是否有内置函数所以我不需要它? 有没有更好的方法来编写选择? 我如何修改例程不需要类。 我可以传递表单对象而不是表单名称作为文本吗? 一般有没有更好的方法?
这是一个完整的页面:
<!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>
【问题讨论】:
标签: javascript jquery