如何在表单中创建html元素,而无需重新加载页面

How to create html elements in a form, without reloading the page?

本文关键字:新加载 加载 表单 创建 元素 html      更新时间:2023-10-23

我正在寻找一种将html元素添加到表单中的方法,例如使用按钮。我一直在看一些例子,但它们非常大(大约是我想要构建的实际表单的3+倍),所以我想知道是否有更好的方法来解决这个问题。

我的想法是这样的:

<form action='blabla.php' method='post'>
    <!-- Insert button here to add a new element -->
    <input type='text' name='desc_1'>
</form>

单击该按钮,应呈现以下内容:

<form action='blabla.php' method='post'>
    <!-- Insert button here to add a new element -->
    <input type='text' name='desc_1'>
    <input type='text' name='desc_2'>
</form>

我希望创建一个新的输入字段,而不需要重新加载页面并释放表单中输入的ev数据。猜测这是我应该通过javascript甚至jquery实现的。我知道如何编辑现有的输入字段,但我不知道如何创建一个新的输入字段并使其遵循其数字范围。有人知道如何用javascript函数来实现这一点吗?或者我应该花点时间研究jquery以获得更流畅的解决方案吗?

您可以进行

html

<button onclick="create();">Create Field</button><br><br>
<form id="frm">
    <input type='text' name='desc_1' placeholder="Input Field 1"><br>
</form>

javascript

var count=1;
function create(){
//alert();
    count++;
    document.getElementById('frm').innerHTML+='<br/><input type="text" id="'+count+'" placeholder="Input Field'+count+'"  /><br/>';
    e.prventDefault();
}

FIDDLE

$("button").click(function(){
    var count = $("input").length + 1;
    
    $("form").prepend("<input type='text' value='desc_" + count + "' name='desc_" + count + "'><br>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<button>add input</button>
<br>
<form action='blabla.php' method='post'>
    <input type='text' name='desc_1'>
</form>

示例

AJAX就是你的答案。它可以让你更新网站内容,而无需反复刷新页面。

XMLhttpRequest可以实现您想要的致敬。http://www.w3schools.com/xml/xml_http.asphttp://www.w3schools.com/dom/tryit.asp?filename=try_dom_xmlhttprequest_first祝好运