动态显示/添加具有不同字段的相同表单到页面

Dynamically display/add the same form to the page with different fields

本文关键字:表单 字段 添加 动态显示      更新时间:2023-09-26

如果在Process按钮旁边添加一个按钮Add more,我的index.jsp会是什么样子,按下该按钮时将显示另一个与上一个相同的搜索表单(如下所示),但具有不同的参数或字段,如ageyear等。 示例:<!-- how will I change the cloned form instead of displaying Car reg: <input type="text" name="car" /> to show age: <input type="text" name="age" /> --> <!-- how will I change the cloned form instead of displaying <input type="button"
onClick="addMoreForm('age')" value="Add More" /> to show <input type="button" onClick="delete('age')" value="delete" /> --> </div>

这可能会让你开始...

您可以创建一个按钮或锚点<a>链接(无论您喜欢哪个)来调用函数:

<input type="button" onClick="addMoreForm('the parameters come here*')" value="Add More" />
  • addMoreForm方法的parameters可能是这样的:formName,fieldName,fieldType,formAction,formMethod等,通过javascript创建表单,这里有一些在javascript中创建元素的链接(<form>是一个元素:-)):
  • http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/
  • 使用 jQuery
  • : jQuery document.createElement 等效?
  • https://stackoverflow.com/a/327068/468763
  • https://stackoverflow.com/a/867981/468763

  • 您可以传递要复制的表单的formNameformId,再次传递一些链接:
  • https://stackoverflow.com/a/921302/468763
  • https://stackoverflow.com/a/710347/468763
  • 使用纯 JavaScript 克隆的示例,我正在克隆您的form1以创建一个form2,其中addingMoreId是一个容器,例如将在其中创建form2<div> 标签:

    var form2 = document.getElementById("form1").cloneNode(true);
    form2.setAttribute("name", "form2");
    form2.setAttribute("id", "form2");
    document.getElementById("addingMoreId").appendChild(form2);
    

PS:为了兼容 crowse-browser,你可以使用像 jQuery 或 YUI 这样的 JavaScript 库。

编辑:这是一个示例代码,您可以在此代码中进行很多改进,也可以使其更加通用。

<input type="button" onClick="addMoreForm('age')" value="Add More" />
<div id="addingMoreId">
    <!-- This is empty, the form2 will be created here -->
    <!-- So it is not required that the form be present here -->
</div>
<!-- This script tag goes into the <head> tag -->
<script>
    // this function will create the form2 in the div
    // you agree or not, you need to learn a lot more about Javascript :-)
    function addMoreForm(fieldName) {
        var form2 = document.getElementById("form1").cloneNode(true);
        form2.setAttribute("name", "form2");
        form2.setAttribute("id", "form2");
        document.getElementById("addingMoreId").appendChild(form2);
        form2.car.setAttribute("name", fieldName); // one way to access the element inside a form: "form2.car", where "car" is the name of the element created inside the form2
        form2.elements[fieldName].setAttribute("id", fieldName); // another way to access the element inside a form: "form2.elements["car"]"
    }
</script>

让我们希望这有帮助:-)