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

时间:2012-08-06 20:23:08

标签: javascript jsp

如果在index.jsp按钮旁边添加按钮Add more,我的Process将如何显示,按下时会显示另一个与之前相同的搜索表单(如下所示)但是使用不同的参数或字段,例如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>

1 个答案:

答案 0 :(得分:0)

这可能会让你开始......

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

<input type="button" onClick="addMoreForm('the parameters come here*')" value="Add More" />

  • 您可以传递要复制的表单的formNameformId,还有一些链接:
  • https://stackoverflow.com/a/921302/468763
  • https://stackoverflow.com/a/710347/468763
  • 使用纯javacript进行克隆的示例,我正在克隆您的form1以创建form2,其中addingMoreId是一个像{<div>这样的容器{1}}标记将创建form2的位置:

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

P.S。:对于众包浏览器兼容性,您可以使用jQueryYUI等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>

希望这有助于: - )