代码之家  ›  专栏  ›  技术社区  ›  rm65453

在另一个文本字段中的数字输入之后,以html形式显示其他文本字段

  •  1
  • rm65453  · 技术社区  · 9 年前

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

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

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

    有没有办法实现这一点?

    谢谢

    1 回复  |  直到 9 年前
        1
  •  2
  •   Little Santi    9 年前

    好的。因此,在按下 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中),并且当表单最终提交时,服务器只会收到一个对名称+值的集合。)