Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...