Get value of upload fields and counting the array - javascript

I have the following html code :
<form name="uploadForm" action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="button" onClick="javascript:submitform();" value="SUBMIT BTN" />
</form>
and here is the javascript function submitform() :
function submitform()
{
var minUpload = 1;
var uploadNo;
var count=document.uploadForm.file_sub.length;
for(a=0;a<count;a++)
{
if(document.uploadForm.file_sub.value != '')
{
uploadNo++;
}
}
if(uploadNo > minUpload){
document.uploadForm.submit();
}else{
alert('Please Upload Atleast ' + minUpload + ' files');
}
}
the javascript is suppose to validate and make sure atleast minUpload of the the file fields a file inside them.
but for some reason when I try to get the length of the file in the function I get an error (according to the debugger of chrome, I get "Uncaught TypeError: Cannot read property 'length' of undefined" ) however I have tried the same thing with checkboxes and it works just fine. What am I doing wrong? is it even possible to do such task in js?

You have to refer to file_sub[]. Fixed function:
var count = document.uploadForm["file_sub[]"].length;
function submitform(){
var minUpload = 1;
var uploadNo;
var files = document.forms['uploadForm']["file_sub[]"];
var count = files.length;
for(var a=0; a<count; a++){
if(files[a].value != ''){
uploadNo++;
}
}
if(uploadNo > minUpload){
document.forms['uploadForm'].submit();
} else {
alert('Please Upload Atleast ' + minUpload + ' files');
}
}

Related

How clear the form inputs after submission?

Already tried everything from different references but, I can't get it to work. I intended to use it for google photo submission form. I just want my text inputs and textarea to clear after it successfully uploaded everything.
Here's the whole HTML code.
<form id="uploaderForm">
<label for="uploaderForm">Photo Upload Form</label>
<div>
<input type="text" name="applicantName" id="applicantName"
placeholder="Your Name">
</div>
<div>
<input type="text" name="gradesection" id="gradesection"
placeholder="Your Grade Level & Section">
</div><br>
<div>
You can select multiple Photos upload!<br>
<br>
<input type="file" name="filesToUpload" id="filesToUpload" multiple>
<br><br>
<input type="button" value="Submit" onclick="uploadFiles()">
</div>
</form>
<br>
<br>
<div id="output"></div>
<script>
var rootFolderId = 'xxxxxxxxxxxxxxxxxxx';
var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;
// Upload the files into a folder in drive
// This is set to send them all to one folder (specificed in the .gs file)
function uploadFiles() {
var allFiles = document.getElementById('filesToUpload').files;
var applicantName = document.getElementById('applicantName').value;
if (!applicantName) {
window.alert('Missing applicant name!');
}
var gradesection = document.getElementById('gradesection').value;
if (!gradesection) {
window.alert('Missing Grade & Section!');
}
var folderName = applicantName + ' - ' + gradesection;
if (allFiles.length == 0) {
window.alert('No file selected!');
} else {
numUploads.total = allFiles.length;
google.script.run.withSuccessHandler(function(r) {
// send files after the folder is created...
for (var i = 0; i < allFiles.length; i++) {
// Send each file at a time
uploadFile(allFiles[i], r.folderId);
}
}).createFolder(rootFolderId, folderName);
}
}
function uploadFile(file, folderId) {
var reader = new FileReader();
reader.onload = function(e) {
var content = reader.result;
document.getElementById('output').innerHTML = 'uploading '
+ file.name + '...';
//window.alert('uploading ' + file.name + '...');
google.script.run.withSuccessHandler(onFileUploaded)
.uploadFile(content, file.name, folderId);
}
reader.readAsDataURL(file);
}
function onFileUploaded(r) {
numUploads.done++;
document.getElementById('output').innerHTML = 'uploaded '
+ r.fileName + ' (' + numUploads.done + '/'
+ numUploads.total + ' files).';
if (numUploads.done == numUploads.total) {
document.getElementById('output').innerHTML = 'All of the '
+ numUploads.total + ' files are uploaded';
numUploads.done = 0;
}
}
</script>
The form upload and displays the response to the user.
I want to reset the form so, the form resets to its original state, so when the user upload another file it wont upload the same file again. Right now, the submission message stays and I have no clue on how to reset the form.
I am new to javascript and I have no clue on what to call to rest the form, any idea? TIA Guys :)
As your code snippet only contains input, You can find all inputs using querySelectorAll and reset its value.
Example below. When you click the button it resets all the input.
function resetAllInput() {
const allInput = document.querySelectorAll('input');
allInput.forEach( input => {
input.value = "";
})
}
function uploadFiles() {
console.log('uploading files');
resetAllInput();
console.log('Resetted all inputs');
}
<form id="uploaderForm">
<label for="uploaderForm">Photo Upload Form</label>
<div>
<input type="text" name="applicantName" id="applicantName" placeholder="Your Name">
</div>
<div>
<input type="text" name="gradesection" id="gradesection" placeholder="Your Grade Level & Section">
</div><br>
<div>
You can select multiple Photos upload!<br>
<br>
<input type="file" name="filesToUpload" id="filesToUpload" multiple>
<br><br>
<input type="button" value="Submit" onclick="uploadFiles()">
</div>
</form>
You can assign null value to your input element:
const reset = () => {
let fileInput = document.getElementById('file-input');
fileInput.value = null;
}
<input type="file" id="file-input">
<button onclick="reset()">Reset</button>

Assign value to an hidden text input with JS

i'm a newbie of JavaScript.
I have that :
HTML:
<form>
<t:inputFileUpload required="true" id="upload" onchange="uploadOnChange()" />
<input id="filename" type="hidden" />
<h:commandButton class="btn btn-primary" value="Upload"
action="#{controller.upload}" />
</form>
javascript:
<script>
function uploadOnChange() {
document.getElementById('upload').onchange = name;
var filename = name;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
document.getElementById('filename').value = filename;
}
</script>
All I want to do is get through a inputFileUpload, to browse my directory, the filename that i've selected, and pass this name as a string to jsf controller.
Does anyone can help me?
EDIT :
If I add to my form enctype="multipart/form-data seems that the controller method "upload" does nothing.
Assuming <t:inputFileUpload> has a value attribute, I'd change the code to something like this:
function uploadOnChange() {
var filename = document.getElementById('upload').value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
document.getElementById('filename').value = filename;
}
console.log('Value hidden input: ' + document.getElementById('filename').value);
}
<input type="file" required="true" id="upload" onchange="uploadOnChange()" />
<input id="filename" type="hidden" />

Get the extension of a file but can't get the filename

I am trying to check if a file has a valid extension or not. The problem is that when I give the file a random extension like .txt it doesn't get caught.
I think the problem is that I am not actually getting the full filename.
<script type="text/javascript">
function getExtension(fileName)
{
var parts = fileName.split('.');
return parts[parts.length - 1];
}
function isVideo(fileName)
{
var ext = getExtension(fileName);
switch (ext.toLowerCase())
{
case 'mp4': return true;
}
return false;
}
function check()
{
var f = document.getElementsByID('file');
if(isVideo(f.value) && document.getElementById('file').value)
{
return true;
}
document.getElementById('errMsg').style.display = '';
return false;
}
</script>
The PHP form:
<?php
$nexturl = "http://localhost/index.php";
?>
<form action="<?php echo($response->url); ?>?nexturl=<?php echo(urlencode($nexturl)); ?>" method="post" enctype="multipart/form-data" onsubmit="return check();">
<input id="file" type="file" name="file"/>
<div id="errMsg" style="display:none;color:red">
Bad file type.
</div>
<input type="hidden" name="token" value="<?php echo($response->token); ?>"/>
<input type="submit" value="go" />
</form>
</php>
You could first obtain the file extension and then do what you need to with it:
var patt1 = /\.[0-9a-z]+$/i;
var fileName = "file.zip";
var theReturn = fileName.match(patt1);
alert(theReturn); //returns .zip
So, in your code, you would need to switch your switch statement to the following:
function isVideo(fileName)
{
var patt1 = /\.[0-9a-z]+$/i;
var fileName = "file.zip";
var theReturn = fileName.match(patt1);
switch (theReturn.toLowerCase())
{
case '.mp4': return true; //make sure it's .mp4 instead of just mp4
}
retrun false
}
EDIT
Example to get file name and extension of uploaded file to FileUpload control:
HTML
<!DOCTYPE Html />
<html>
<head>
<title></title>
</head>
<body>
<input id="File1" type="file" />
<input type="button" id="btnGetExt" value="Get File Extension"/>
<script type="text/javascript" src="theJS.js"></script>
</body>
</html>
JavaScript
btnGetExt.onclick = function () {
var patt1 = /\.[0-9a-z]+$/i;
var fileName = document.getElementById('File1').value;
alert(fileName);
var theReturn = fileName.match(patt1);
alert(theReturn);
}

Displaying range validator error message on html input

I have an input type =text in html and i have this js code in js file to show error message
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
var toReturn = 0;
$("input", $form).each(function () {
if ($(this).val() == "") {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = 1;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
I am trying to convert this code to make range validator on input type=text field .dispalying only 5 digits in the textbox, but i couldn't achieve . Is there any easy way to do this ?
Thanks
Consider using the jQuery validation plugin instead, especially the rangelength method for your case. However, if you want to stick to the original code without using any library then I suggest you try the code below for example:
HTML:
<form id="myid" name="myid" method="post" action="/">name :
<input type="text" name="name" id="name" />age :
<input type="text" name="age" id="age" />
<input type="submit" id="submit" name="submit" value="Save" />
</form>
jQuery:
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
$("#submit").on("click", function () {
var toReturn = true;
$("input", $form).each(function () {
var value = $(this).val();
if((!$.trim(this.value).length) || (value.length > 5)) {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = false;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
return toReturn;
});
Working JSFiddle Demo

jQuery Multiple File Upload Plugin check wheather empty or not

I have downloaded JQuery Multiple file uploader from this site
http://www.fyneworks.com/jquery/multiple-file-upload/
I need to check whether the file input field is null or not before submitting the form.
<form onsubmit="return validate();">
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="submit" name="BtnSubmit" value="save" />
</form>
I tried
function validate() {
$(".multi").each(function () {
var multi = $(this).val();
if (multi) {
return true;
} else {
return false;
}
});
}
Not working because the filed is always empty. So is there any other way to achieve this ?
try this
var multi = $(".multi").val();
if (multi) {
console.log("multi");
} else {
console.log("no multi");
}
fiddle:
http://jsfiddle.net/w4qVv/
UPDATE:
or you can do it like this
function validate(field) {
var fieldVal = $(field).val();
if(!fieldVal) alert("No files selected");
}
and then:
validate(".multi");
fiddle:
http://jsfiddle.net/jk8aZ/
UPDATE2:
yep, you can use each like this
var multi = (".multi");
$(multi).each(function () {
validate(this);
});
fiddle:
http://jsfiddle.net/jk8aZ/1/

Categories

Resources