-1

hello i try to find a good solution to limit number of file in file input my problem is i need too find a generic solution because html is dynmaic generation and i have multi input in same page (and i want different limit peer field) html code previwe

<input type="file" name="micker[file_upload2][]" accept=".pdf" id="fileupload2" placeholder="Upload field2 mulitple" aria-label="Upload field2 mulitple" class="inputfile required invalid" multiple="" style="margin:0" maxuploads="2" aria-required="true" required="required" aria-invalid="true">

i need to add limit function peer field like first 2 and second 10 my idea is to inspire to https://stackoverflow.com/a/15855085/2822359 adding max-uploads = 6 to my html and upload.js

jQuery(document).ready(function ($) {
           $("body").change(function () {
               var numFiles = $("input",this)[0].files.length;
               var maxuploads = $("input",this)[0].attr(\'data-maxuploads\').toString();
               alert(numFiles);
               if (numFiles > maxuploads ) {
                   alert(\'Your Message\');
                   }else {
                   maxuploads = maxuploads + 1;
                       }
                   });
           });
           });

the error

Uncaught TypeError: Cannot read property 'length' of undefined

thanks for any help

yberges
  • 13
  • 1
  • 7
  • `max-uploads` tries to subtract the value of the variable `uploads` from the value of `max`. `'max-uploads'` is something completely different … – CBroe Mar 26 '20 at 10:14
  • i change max-uploads for maxuploads now i have this error ```upload.js:4 Uncaught ReferenceError: maxuploads is not defined at HTMLInputElement. (upload.js:4) at HTMLInputElement.dispatch (jquery.min.js?ef23cc6c642e3e837ae5b5b80ea7e78e:2) at HTMLInputElement.v.handle (jquery.min.js?ef23cc6c642e3e837ae5b5b80ea7e78e:2)``` – yberges Mar 26 '20 at 10:35
  • `maxuploads` is still the refernce to a variable. You want to pass a _text literal_ (vulgo: “string”) to the function here, that was the point I was trying to make clear to you … – CBroe Mar 26 '20 at 10:41
  • maybe the code is totaly wrong ... did you have an other proof ? – yberges Mar 26 '20 at 10:48
  • Or maybe you just need to learn some of the absolute syntax basics of the language you intend to use here. Are you really not aware of the difference between `foo` and `'foo'` in JavaScript …? – CBroe Mar 26 '20 at 10:51
  • sorry my english is little limited lol i try to learn ... i kknow difference between foo and 'foo' but i don't understand context ... sorry – yberges Mar 26 '20 at 11:03
  • `.attr(foo)` would require that a variable named `foo` exists, and that that variable contains the actual name of the attribute you want to read here. `.attr('bar')` however directly passes the _text_ value `bar` _as_ the name of the attribute to look for. – CBroe Mar 26 '20 at 11:07
  • hello i update my first post with update my code => maxupload attrb is added => js code is update => error return – yberges Mar 26 '20 at 13:38
  • That’s because you are still referring to a _variable_ in that place. This needs to be `$(this).attr('maxuploads')`, with a _string value_ in that place, not a non-existing variable. – CBroe Mar 26 '20 at 13:54
  • ok no more error ... but limitation doesn't works no message ... but i am not sure about var number_of_uploads ... nothing is define here ?? how i can find number of file select in input to campare ? – yberges Mar 26 '20 at 14:06
  • That variable should probably be properly initialized with `0`, otherwise the script will try to add 1 to `undefined` , which will probably result in `NaN` – CBroe Mar 26 '20 at 14:34
  • i try to change for `jQuery(document).ready(function ($) { var number_of_uploads; $("#fileupload2").change(function () { if ($("#fileupload2").files.length > $(this).attr(maxuploads)) { alert(\'Your Message\'); } else { number_of_uploads = number_of_uploads + 1; } }); }); ` – yberges Mar 26 '20 at 15:23
  • i udpate my initial code to be more clear i hope @CBroe – yberges Mar 30 '20 at 13:51
  • Is this actually the first input field in your whole document (in DOM order)? Or are you maybe accessing a field that is not actually of `type="file"` now there? – CBroe Mar 30 '20 at 14:01

1 Answers1

0

Maybe this answers your question: https://www.tutorialspoint.com/How-to-limit-maximum-items-on-multiple-input-input-type-file-multiple

Here is a little working snippet generated along those lines. I take the maximum allowed numbers of files from the data-max attribute of each individual input element.

Edit: I now trigger the file-count-check by the change event of each file input (I use "delegated binding", i. e. the listener is attached to the parent <form> element). Depending on whether the maximum number is exceeded I disable the submit-button.

const btn=document.querySelector('input[type=submit]');
document.querySelector('form').addEventListener('change',function(ev){
 if(ev.target.type=='file'){
  // I collect the inps here to allow for dynamic pages (varying number of inputs):
  const inps=[...document.querySelectorAll('input[type=file]')];
  btn.disabled=inps.some(inp=>{ // check whether the condition has been violated at least once
    if (inp.files.length>inp.dataset.max){ // show warning for first violation
      console.log(`You are only allowed to upload a maximum of ${inp.dataset.max} files for ${inp.name}!`);
      return true;
    }
  })
 }
});
<html>
   <head>
      <title>HTML file upload</title>
   </head>
   <body>
      <form>
         <input type="file" name="files1[]" accept=".pdf" multiple data-max="2"><br/>
         <input type="file" name="files2[]" accept=".pdf" multiple data-max="3"><br/><br/>
         Upload multiple files, and click Submit.<br>
         <input type="submit" value = "submit">
      </form>
   </body>
</html>
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
  • Very cooooooolllll that works !!!!!! 2 questions : - adaptable to listen each input field without submit ? - its possible to to change {inp.label} in message ? – yberges Mar 31 '20 at 07:44
  • about label i found ! – yberges Mar 31 '20 at 08:44
  • Sorry to hear ... It works in the snippet here - in the form that the submit button gets disabled and a warning is shown below in the console. What does your console say? – Carsten Massmann Mar 31 '20 at 12:24
  • its realy strange console say nothing no error ..... but submit isn't disable and form ask html5 require function in other field – yberges Mar 31 '20 at 12:51