简体   繁体   中英

How to Dynamically create Form elements

I need to dynamically create a form when user enter the number of row.

I tried the below code and spent over an hour searching on internet and can't solve that.

I was first of all doing it using PHP and I got stuck along the way, and people on the forum advised me to use Javascript.

I'm now confused !! Please give me a clue !

 <p> <h3>Assignment 11]</h3>***********************</p> <form action="" method="post"> <b>Number of items</b> (between 1 and 30): <input type="number" name="numbItems" min="1" max="30" id="numbItem"> &nbsp&nbsp <input name="submit" value="Create" type="submit" id="createItem"> </form> <script type="text/javascript"> //document.getElementById("numbItem").onchange = function() { document.getElementById("createItem").onclick = function() { var price = document.getElementById("numbItem").value; //document.getElementById("demo").innerHTML = "your model price will be " + price ; alert(price + " items created."); }; </script> <br>=============================================================================<br><br> <table> <tr> <td>Item</td> <td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspValue ( R )</td> <td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspTaxes ( R )</td> <td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspVAT ( % )</td> </tr> </table> <br>=============================================================================<br><br> <?php if($numbItems=="1") { ?> <form action="" method="post"> <input type="text" name="item1" placeholder="Eg: Gross Salary" />&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="value1" placeholder="Eg: 12000" />&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type="text" name="tax1" value="" readonly style="color:#f00;background:#ccc">&nbsp&nbsp&nbsp&nbsp&nbsp<input type="number" name="vat1" min="0" max="100"> &nbsp&nbsp&nbsp&nbsp&nbsp <input name="btnItem1" value="Calculate" type="button"><br><br> </form> <?php } ?> <?php if($numbItems=="2") { ?> <form action="" method="post"> <input type="text" name="item1" placeholder="Eg: Gross Salary" />&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="value1" placeholder="Eg: 12000" />&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type="text" name="tax1" value="" readonly style="color:#f00;background:#ccc">&nbsp&nbsp&nbsp&nbsp&nbsp<input type="number" name="vat1" min="0" max="100"> &nbsp&nbsp&nbsp&nbsp&nbsp <input name="btnItem1" value="Calculate" type="submit"><br><br> <input type="text" name="item2" placeholder="Eg: Electricity" />&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="value2" placeholder="Eg: 750" />&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type="text" name="tax2" value="" readonly style="color:#f00;background:#ccc">&nbsp&nbsp&nbsp&nbsp&nbsp<input type="number" name="vat2" min="0" max="100"> &nbsp&nbsp&nbsp&nbsp&nbsp <input name="btnItem2" value="Calculate" type="submit"><br><br> <!-- <input type="submit" value="Submit"> --> </form> <?php } ?> 

if you have jQuery...
1.Add id element to the form or create a new DIV as follow

<form action="" method="post">
    <div id="theForm"></div>
</form>

2.The jQuery function

$('#createItem').click(function(e){  
    $('#theForm').append('<< Your Items HTML Code >>')  
});

3.Change the name elements to item[] instead of item1 and the others

When you call $_POST['item'] in PHP, the item will be read as an array. You can get all the items with a

$items = $_POST['item'];
foreach($items as $item){
    echo $item; //Output the value
}

This will help you. Good luck

 $(document).ready(function(e) { $("#create").on("click",function(){ var num = $("#num").val(); if(num>1){ for(i=1; i<=num; i++){ $(".extra").append('<tr><td><input type="text"></td></tr>'); } }else{ $(".extra").append('<tr><td><input type="text"></td></tr>'); } }); }); 
 <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <input type="number" id="num"> <button type="button" id="create">Create</button> <table> <tbody class="extra"> </tbody> </table> 

Check this following code. I've used Jquery to do this. If you've quite bit easy with javascript you can able to understand it. Hope, it'll help you to understand how u can handle such situation in Javascript.

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript">
    $( document ).ready(function() {
        console.log( "ready!" );

        $( "#createItem" ).click(function() {
            var totalRows = $('#numbItem').val();

            var formHtml = '';
            for (var i = 1; i <= totalRows; i++)
            {
                formHtml += '&nbsp;<input type="text" name="item'+i+'"  placeholder="E.g.: Gross Salary" />&nbsp;<input type="text" name="value'+i+'" placeholder="E.g.: 12000" />&nbsp;<input type="text" name="tax'+i+'" value="" readonly style="color:#f00;background:#ccc">&nbsp;<input type="number" name="vat'+i+'" min="0" max="100">&nbsp;<input name="btnItem'+i+'" value="Calculate" type="button"><br><br>';

            }

            $('#userForms').html(formHtml);
        });

    });
</script>
</head>
<body>

    <b>Number of items</b> (between 1 and 30):
    <input type="number" name="numbItem" min="1" max="30" id="numbItem"> &nbsp&nbsp
    <button id='createItem' type="button">Create</button>

    <div id=userForms></div>

</body>
</html>

I'll point out somethings, tag

    <hr>

is the html way to place separation you want.

When Using table, try to use thead,tbody and tfoot as it gives a straightforward way to add elemnts withoud touching headers or footers.

As for the main question, JQuery is powerfull but if you are a newbie, not knowing the basics will give you problems in the future. So as there are vere good JQuery answers here, here is a plain javascript solution

 <html> <body> <p> <h3>Assignment 11</h3> <hr> <form action="" method="post"> <p> <b>Number of items</b> (between 1 and 30): </p> <input type="number" name="numbItems" min="1" max="30" step="1" id="numbItem"> <br> <input name="submit" value="Create" type="button" id="createItem"> </form> <hr> <table> <thead> <tr> <td>Item</td> <td>Value ( R )</td> <td>Taxes ( R )</td> <td>VAT ( % )</td> </tr> </thead> <tbody id="itemsTableBody"></tbody> <tfoot> <tr> <td>Item</td> <td>Value ( R )</td> <td>Taxes ( R )</td> <td>VAT ( % )</td> </tr> </tfoot> </table> <script type="text/javascript"> document.getElementById("createItem").onclick = function() { var price = document.getElementById("numbItem").value; var tbody = document.getElementById("itemsTableBody"); var olds = tbody.childNodes; for (; olds.length > 0;) { tbody.removeChild(olds[0]); } for (var i = 0; i < price; ++i) { var tr = document.createElement("tr"); var td1 = document.createElement("td"); var td2 = document.createElement("td"); var td3 = document.createElement("td"); var td4 = document.createElement("td"); td1.appendChild(document.createTextNode("td1 " + i)); td2.appendChild(document.createTextNode("td2 " + i)); td3.appendChild(document.createTextNode("td3 " + i)); td4.appendChild(document.createTextNode("td4 " + i)); tr.appendChild(td1); tr.appendChild(td2); tr.appendChild(td3); tr.appendChild(td4); tbody.appendChild(tr); } }; </script> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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