After clicking on button incrementBtn there is html input file type created in div attachments by this Javascript function:
var counter = 0;
var incrementBtn = document.getElementById('incrementBtn');
var attachments = document.getElementById('attachments');
var createNewFiled = function() {
counter++;
if (counter <= 10) {
var input = document.createElement("input");
var br = document.createElement("br");
var br2 = document.createElement("br");
input.id = 'file'+counter;
input.classList.add("inputClass");
input.type = 'file';
input.name = 'file'+counter;
attachments.appendChild(input);
attachments.appendChild(br);
attachments.appendChild(br2);
}
else {
alert('Ten attachments is max.');
}
};
HTML:
<div id='attachments'></div><button onclick='createNewFiled()' id='incrementBtn' type='button'>+</button>
I would like to check file size before POST (I have check also after POST by PHP, but if max file size in php.ini is exceeded, POST will fail and user is not notified about it…)
I tried to add line input.onchange = 'upload_check()'; after input.name = 'file'+counter; in createNewFiled function but as I can see in browsers dev tools, onchange is not there. This is created after button click:
<input id="file1" class="inputClass" type="file" name="file1">
This is upload_check function (it just checks file1 for testing purposes):
function upload_check() {
var upl = document.getElementById("file1");
var max = 1000000;
if (upl.files[0].size > max) {
alert("File too big!");
upl.value = "";
}
};
What am I doing wrong?
>Solution :
This is not right:
input.onchange = 'upload_check()';
This attempts to set an HTML attribute, but you are actually setting a property of the input element (which is actually good), and in that case you should not assign a string, but assign the function (object) itself. So:
input.onchange = upload_check;
It is better practice to attach an event handler with addEventListener, because that allows you to have more than one handler for the same event:
input.addEventListener("change", upload_check);