繁体   English   中英

从用户输入中添加HTML表单字段

[英]Adding html form fields from user input

我有一张表格,要求用户给设备类型命名,并说出他们想分配给该设备类型多少个属性。 该表格调用以下php文件,该文件使用循环创建所需数量的属性。

我使用了name =“ attribute”。$ i,以便能够识别下一个php页面上的每个属性,以将信息发送到数据库。

<?php echo $_POST['device-name']; ?>

    <?php 

        $num=$_POST['number-of-attributes'];
        $num=intval($num);

        for($i=0; $i<$num; $i++) {

            newAttribute($i);

        }

        function newAttribute($i) {

            echo ("<div id=\"new-attribute\">");
            echo ("<h3>New Attribute</h3>");
            echo ("<label for=\"attribute".$i."\">Name</label>");
            echo ("<input id=\"attribute\" type=\"text\" name=\"attribute".$i."\">");
            echo ("</div>");

        }

    ?>

但是我也希望用户能够单击例如:

<div id="small-button">New Attribute</div>

并创建另一组字段以定义属性。

我该怎么做?

提前致谢

您需要JavaScript才能完成上述工作。 在HTML文档中,在body元素的末尾添加以下script元素

<script type="text/javascript">

var numberOfAttributes = 1;

function newAttributeFields(e) {
    // Creates the div
    var div = document.createElement('div');
    div.id = 'new-attribute';

    // Appends the fields
    div.innerHtml = '<h3>New attribute</h3><label for="attribute' + numberOfAttributes + '">Name</label><input id="attribute" type="text" name="attribute' + numberOfAttributes + '">';

    // Appends it to the body element
    document.getElementsByTagName('body')[0].appendChild(div);

    // Increments the number of attributes by one
    numberOfAttributes = numberOfAttributes + 1;
}

var smallButton = document.getElementById('small-button');

// When the 'small button' is clicked, calls the newAttributeFields function
smallButton.addEventListener('click', newAttributeFields, false);

</script>

在客户端使用javascript / jquery:

var template = "<div class=\"new-attribute\">"
             + "<h3>New Attribute</h3>"
             + "<label for=\"attribute\">Name</label>"
             + "<input id=\"attribute\" type=\"text\" name=\"attribute\">"
             + "</div>";

$(document).ready(function() {
// The DOM has loaded
    $("#small-button").on('click', function() {
    // The user clicked your 'New Attribute' button
        // Append a new attribute to the <body> with `template` we defined above:
        $(body).append(template);
    });
});

注意:我将id="new-attribute"更改为class="new-attribute"因为将有1个以上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM