How to create more form fields by using javascript and then passing values to PHP

两盒软妹~` 提交于 2019-12-13 09:47:33

问题


Hi I'd like to make it so that the user can click a "upload more files" button to create an additional file upload form field and they can also click another button called "add more names" to create an additional "input type='text'" form field.

There should be a limit on how many file upload or text fields that can be created using their respective buttons. For example, there should be a max number of 5 file upload fields and a max number of 5 text fields.

After the user clicks the "submit" button, the script will record the total number of file upload and text form fields and pass those numbers to PHP. For example, if there are 5 file upload and 5 text form fields, the variable $numfiles will record the number of file upload fields and the variable $numtext will record the number of text fields.

A sample code would be great, thanks.


回答1:


maybe something like this:

var totalFields = <?=$total_fields?>;
var currentFields = 0;

var addMode = document.getElementById('addMore');
var form = docuement.getElementsByTagName('form')[0];

addMore.onclick = function() {
   if (currentFields >= totalFields) {
      return false;
   }
   var newField = document.createElement('input');
   newField.setAttribute('type', 'file');
   newField.setAttribute('name', 'file'+currentFields);
   form.appendChild(newField);
   currentFields++
}

and then

<?
   foreach ($_FILES as $file) {
      // i guess you know what you should do
   }
?>

not tested ... just for example



来源:https://stackoverflow.com/questions/6269145/how-to-create-more-form-fields-by-using-javascript-and-then-passing-values-to-ph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!