【问题标题】:additional text fields in html form after a numeric entry in another text field在另一个文本字段中输入数字后,html 表单中的附加文本字段
【发布时间】:2015-08-02 15:45:08
【问题描述】:

我正在使用 html 表单使用 php 将数据发送到 sql 数据库。

我的问题是我有一个动态的项目数量值,每个订单都会发生变化,并且试图避免为所有订单添加 x 个额外的文本字段。

更好的解决方案是在文本字段中输入一个值,然后在表单中显示相同数量的附加文本字段。

有没有办法做到这一点?

谢谢

【问题讨论】:

  • 您是否要开发一个网页,为每次使用显示不同个输入字段(应用户要求)?
  • 是的,但我希望在不按下提交按钮的情况下发生这种情况。

标签: text dynamic field


【解决方案1】:

好的。因此,您希望在按下submit 按钮之前,根据用户的请求显示一些输入字段。我的第一种方法是在javascript中

让我们假设这种形式:

<form>
<p><input name="myInput1" /></p>
<button type="submit">submit</button>
</form>

您可以包含一个额外的按钮来添加新行:

<form>
<p><input name="myInput1" /></p>
<button type="button" onclick="addInput(this.form)">add input</button>
<button type="submit">submit</button>
</form>

... 处理函数将是这样的:

<script type="text/javascript">
function addInput(form)
{
    // Create a new <p><input> node at the end of the form, throughput the DOM API:

    // Get the last <p> element of the form
    var paragraphs=form.getElementsByTagName("P")
    var lastParagraph=paragraphs[paragraphs.length-1]

    // Create a new <p> element with a <input> child:
    var newParagraph=document.createElement("P")
    var newInput=document.createElement("INPUT")
    // Name the <input> with a numeric suffix not to produce duplicates:
    newInput.name="myInput"+(1+paragraphs.length)
    newParagraph.appendChild(newInput)

    // Add the created <p> after the last existing <p> of the form:
    form.insertBefore(newParagraph, lastParagraph.nextSibling)
}
</script>

(注意所有的渲染逻辑在客户端(在HTML + javascript中),当表单最终提交时,服务端会收到一个name + value对的集合.)

【讨论】:

  • 太棒了,如果你不介意,你能解释一下 "var paragraphs=form.getElementsByTagName("P") var lastParagraph=paragraphs[paragraphs.length-1] var newParagraph=document.createElement( “P”)”部分。谢谢
  • 当然。我在答案中添加了一些 cmets。
  • 而且,如果您是 DOM API 新手,我建议您阅读官方文档:developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model1
猜你喜欢
  • 1970-01-01
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多