PHP Stop Form Reload Show Error Js - javascript

I want to show my error if 'fileToUpload' is empty (show error with js) and stop reloading page if 'fileToUpload' is empty
<form method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input class='new_post' type="submit" value="Upload Image" name="submit">
</form>
$('.new_post').click(function() {
var get_photo = $('#fileToUpload').get(0).files.length;
// If 0 file show error
if (get_photo == 0) {
openandclose('.error_box' , 'emptyyyy.', 1700);
$('.error_box').focus();
return false;
}
});

Add an id to your form like this <form method="post" enctype="multipart/form-data" id="myform"> and in your javascript attach the checking function as callback to the form submit event rather than button click event like $('#myform').submit().
$('#myform').submit(function() {
var get_photo = $('#fileToUpload').get(0).files.length;
// If 0 file show error
if (get_photo == 0) {
/*
openandclose('.error_box', 'emptyyyy.', 1700);
$('.error_box').focus();
*/
alert("EMPTY!!");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" enctype="multipart/form-data" id="myform">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input class='new_post' type="submit" value="Upload Image" name="submit">
</form>

This code might help you out.Upon clicking the button it checks for whether file is selected or not , and return True/False Accordingly.
<form method="post" enctype="multipart/form-data" onsubmit="return funccheck();">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input class='new_post' type="submit" value="Upload Image" name="submit"> </form>
<script>
function funccheck() {
var get_photo = $('#fileToUpload').get(0).files.length;
// If 0 file show error
if (get_photo == 0) {
openandclose('.error_box' , 'emptyyyy.', 1700);
$('.error_box').focus();
return false; //stops page loading
}
return true; // initiates page loading
});
</script>

Try this:
$('.new_post').click(function(e) { var get_photo = $('#fileToUpload').get(0).files.length; // If 0 file show error if (get_photo == 0) { openandclose('.error_box' , 'emptyyyy.', 1700); $('.error_box').focus();
e.preventDefault();
return false; } });
The variable e is the event, the function preventDefault will stop the form from submitting if there is no file.

Related

jQuery - Auto submit form

I want to auto submit form which flow is like below.
input type = 'file' should not display.
if click on submit button choose file pop up should open.
after selecting a file form should auto submit with validation.
I complete most of this but facing problem while submitting form.
NOTE -> i hide input type = 'file' using css style.
Here is my HTMLfrom
<form method="post" class="form" action="<?php echo base_url('csv/store'); ?>" enctype="multipart/form-data">
<input type="file" id="myfile" name="myfile" accept=".csv" style="display:none">
<br/>
<input type="submit" class="submit btn btn-primary" value="Import csv"/>
</form>
This is my javaScript
<script>
$(document).ready(function(){
function validation() {
//validation here
}
$('.submit').click(function(event) {
event.preventDefault();
$('#myfile').click();
});
});
</script>
Is this what you want?
$(document).ready(function(){
function validation() {
//validation here
alert('in function validation')
$('#myForm').submit();
}
$('.submit').click(function(event) {
event.preventDefault();
$('#myfile').click();
});
$('#myfile').on('change',function(){
validation();
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" class="form" id="myForm" action="<?php echo base_url('csv/store'); ?>" enctype="multipart/form-data">
<input type="file" id="myfile" name="myfile" accept=".csv" style="display:none">
<br/>
<input type="submit" class="submit btn btn-primary" value="Import csv"/>
</form>
Instead of using the submit button, give the hidden input type="file" a <label> element and style that as a button. This will make it look like a submit button, but will instead prompt the file upload.
Then listen for the change event on the hidden file input. This event will be fired every time you upload a file. There you'll want to do validation. If the validation succeeds, manually submit the form with the jQuery .submit() method.
$(document).ready(function() {
function validation(files) {
//validation here, now returns true for demonstration.
return true;
}
$('#myfile').change(function(event) {
// Check if files are valid.
const isValid = validation(event.target.files);
// If the are..
if (isValid) {
// ..submit the form.
$('#myform').submit();
}
});
});
.btn {
display: inline-block;
padding: 0.5rem;
border: 1px solid #d0d0d0;
border-radius: 3px;
background-color: #f0f0f0;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform" method="post" class="form" action="<?php echo base_url('csv/store'); ?>" enctype="multipart/form-data">
<label for="myfile" class="submit btn btn-primary">Import CSV</label>
<input type="file" id="myfile" name="myfile" accept=".csv" style="display:none">
</form>

Onsubmit event after javascript form submit

I have an upload file form, and i try to upload the file when it's selected,so i tried something like this:
<form enctype="multipart/form-data" method="POST" onsubmit="return
UploadFile(this);">
<input id="upfile" type="file" onchange="this.form.submit();"/>
</form>
The form.submit() works , but of course i need to do some validation on submit,so i tried to run a function:
function UploadFile(file){
alert('Bleah');
return false;
}
On normal circumstances it should return false, and the form shouldn't reload the page,but this doesn't happens.
If i add a submit input into the form, it works as expected:
<form enctype="multipart/form-data" method="POST" onsubmit="return
UploadFile(this);">
<input type="submit" name="upload" value="Upload">
<input id="upfile" type="file"/>
</form>
Can anyone explain me what is wrong please?
Try this:
function UploadFile(file) {
if (file.value === '') {
alert("Invalid File");
} else {
alert('Form will be submitted now!');
document.getElementById('myForm').submit();
}
}
<form enctype="multipart/form-data" method="POST" id="myForm">
<input id="upfile" name="upfile" type="file" onchange="UploadFile(this);" />
</form>
To upload the file when it's selected, you must call UploadFile() function on the input change, not on the form change tag. If you submit on input change, the page gets reloaded.
So, you'd better use something like this:
$('#upfile').onchange(function(){
if(UploadFile(this.parent('form'))){
this.parent('form').submit();
}
})
And you won't need onchange and onsubmit inside the tags any more.
Solution:
<form id="formname" enctype="multipart/form-data" method="POST" action="test.html">
<input id="upfile" type="file" onchange="sendForm()"/>
</form>
<script>
function sendForm() {
var field = document.getElementById("upfile");
if (field) {
console.log("the is a file and the form will be sent");
document.forms["formname"].submit();
}
}
</script>
OLD--
I dont understand, how would you like to submit the form without a submit button? or at least, handle the submission in javascript "object.addEventListener("keydown", myScript);"
--
ok, I read it once again and I understand the question
You need to handle this on javascript and detect the selection of the file. Look at this thread:
how to check if a file is selected using javascript?

form "submit" event disabled on IE

I encounter a problem with a file upload form when I use Internet Explorer (9).
My form is a little special because I simulate a secondary behavior on my both inputs :
For the input[type=file], after the user selects a file, I submit the form.
For the input[type=submit], before he submits the form, I open the file browser and once he selects a file, I submit it.
The my script works with Chrome and FF but not IE. Indeed when I test the submit button the form is not sent whereas when I use the input[type=file], I don't have any problems.
Here is the HTML:
<form name="up" action="/" method="post" enctype="multipart/form-data">
<div class="fileinputs">
<input type="file" name="FILE" size="38" class="file" id="upload" onchange="submitForm()" />
<input type="submit" value="BROWSE" name="ok" class="submit" id="submit_button_id" onclick="return check();" />
</div>
</form>
JS :
function submitForm() {
document.getElementById("submit_button_id").click();
}
function check()
{
var path = false;
document.getElementById('upload').click();
var filesent = document.getElementById("upload");
filesent.value === "" ? path = false : path = true;
if(!path){
return false;
}
return true;
}

JQuery Validate Multiple files

Hi I have a multiple files to upload, I need to validate all these before submitting the form
<form onsubmit="return validate()">
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="submit" name="BtnSubmit" value="save" />
</form>
And the j query part
function validate()
{
$(".multi").each(function(){
var files = $(this).val();
if(files=='')
{
alert("No document file selected");
return false;
}
});
}
The problem is its showing the alert but still it submitting the form. How to prevent this.?
The validate function is not returning false, but the .each() function is. So add validation to check if all validation passed in .each() function, otherwise return false
function validate() {
var count = $(".multi").length;
var index = 0;
$(".multi").each(function () {
var files = $(this).val();
if (files == '') {
alert("No document file selected");
return false;
}
index += 1;
});
if (index != count) { //If the validation in .each() looping has returned false
return false;
}
}
Returning false from the onsubmit handler of the form stops the submission process, but in your code you are returning false from the anonymous function you are giving to $.each instead of validate function.
Try out this fiddle http://jsfiddle.net/6cU74/3/
HTML:-
<form id="form1" method="post">
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="file" name="File" class="multi" />
<input type="submit" id="BtnSubmit" value="save" />
</form>
JS(Using jQuery):-
$(function () {
$("#BtnSubmit").click(function (event) {
event.preventDefault();
var flag = true;
$(".multi").each(function () {
var files = $(this).val();
if (files == '') {
alert("No document file selected");
flag=false;
}
});
if (true==flag){
$("#form1").submit();
}
});
});

Hide the upload submit button if field "file" is empty

With this simple example
<form action="" method="post" enctype="multipart/form-data">
Upload images: <input type="file" name="images[]" multiple="multiple"> <input type="submit" name="submitImgs" value="Upload"/>
</form>
How can I hide the submit button until somthing's in the file field, I've tried to make a php script that look if the $_FILES['error'] == 4 or is_file_uploaded, etc and that don't work. So I want to simply hide the button until something is selected in the file field.
The answer could be in javascript, jQuery... I don't care :D
Thanks
The <input type="file"> element has a files property.
Simply check files.length.
jQuery example, which modifies the submit button on the fly:
// Select the <input type="file"> element
$('input[type=file][name="images[]"]').change(function(){
var hasNoFiles = this.files.length == 0;
$(this).closest('form') /* Select the form element */
.find('input[type=submit]') /* Get the submit button */
.prop('disabled', hasNoFiles); /* Disable the button. */
});
Use this. Attach the code on the change event of the file field.
$(function() {
$("input:file").change(function() {
var fileName = $(this).val();
if(filename != "") { $("#submitButtonId").show(); } //show the button
});
});
The default state of the submit should be hidden (CSS display: none)
And on change event of the file field, you show that submit button
Her's the code
<script>
$(function() {
$("#myfileinput").change(function() {
if($(this)).val() != "") $("submit").show();
});
});
</script/>
<form action="" method="post" enctype="multipart/form-data">
Upload images: <input id="myfileinput" type="file" name="images[]" multiple="multiple">
<input type="submit" name="submitImgs" value="Upload" style="display:none"/>
</form>
<script>
function checkFile() {
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
if(size > 0) {
document.getElementById('submit').style.display='block';
}
}
</script>
<form action="" method="post" enctype="multipart/form-data">
Upload images: <input type="file" onChange="checkFile()" name="images[]" multiple="multiple"> <input type="submit" style="display:none;" name="submitImgs" value="Upload" id="submit" />
</form>

Categories