简体   繁体   中英

Dynamic Rows for Table in a Form

I'm trying to create a form that can dynamically add more rows to a table as needed. In the example that I will post you will see a table for chaperones. Since, we do not know off hand how many chaperones each school will bring it needs to be dynamic. I'm trying to use Javascript to create an onclick button that will add a new row to the table and storing the names as an array so that it can be sent POST and analyzed using PHP and then stored into the database. I found a solution online, however when I try to implement it on my site nothing is working once I click the button. Maybe I just need another set of eyes to look it over and see if I need anything.

  <table id="chp" class="table table-striped"> <tr> <th class="text-center">First Name</th> <th class="text-center">Last Name</th> <th class="text-center">Phone</th> <th class="text-center">Email</th> <th class="text-center"> + </th> </tr> <tr> <td><input id="chpFirst" name="chpFirst" type="text" placeholder="John" class="form-control input-md" required=""></td> <td><input id="chpLast" name="chpLast" type="text" placeholder="Doe" class="form-control input-md" required=""></td> <td><input id="chpPhone" name="chpPhone" type="text" placeholder="5555555555" class="form-control input-md" required=""></td> <td><input id="chpEmail" name="chpEmail" type="text" placeholder="john.doe@email.com" class="form-control input-md" required=""></td> <td><input type="button" id="more_fields" onclick="add_chp();" value="Add" class="btn btn-info" /></td> </tr> </table> <script> function add_chp() { document.getElementByID("chp").insertRow(-1).innerHTML = '<tr>' + '<td><input id="chpFirst" name="chpFirst[]" type="text" placeholder="John" class="form-control input-md" required=""></td>' + '<td><input id="chpLast" name="chpLast[]" type="text" placeholder="Doe" class="form-control input-md" required=""></td>' + '<td><input id="chpPhone" name="chpPhone[]" type="text" placeholder="5555555555" class="form-control input-md" required=""></td>' + '<td><input id="chpEmail" name="chpEmail[]" type="text" placeholder="john.doe@email.com" class="form-control input-md" required=""></td>' + '<td><input type="button" id="more_fields" onclick="add_fields();" value="Add More" class="btn btn-info" /></td>' + '</tr>'; } </script> 

https://jsfiddle.net/owk9ct13/

JavaScript is case sensitive: document.getElementByID wont work. Replace that with document.getElementById and it should fix your issue.

Also as a tip, be sure to check the any error or warning messages in the browser console...it makes debugging the front end way easier. 您的错误图片

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