I have a PHP script to upload image on my form. It is functioning properly. I have 2 buttons, one to browse for the file (to be uploaded) and the other is a submit button that displays this image on the screen.
I want that on clicking Browse --> selecting file --> clicking OK, the file should get uploaded. Do not need the extra "submit" button.
I am just pasting a part of my code here, that represents these buttons.
<div class="upload_container">
<br clear="all" />
<div id='preview'></div>
<form id="image_upload_form" enctype="multipart/form-data" action="<?php
echo $_SERVER['PHP_SELF'];
?>" method="post" class="change-pic">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<input style="padding-left:20px; color:#4d4d4d" type="file" id="file" name="user_image" accept="image/*" />
<script type="text/javascript">
document.getElementById("file").onchange = function() {
document.getElementById("image_upload_form").submit();
};
</script>
</form>
</div>
</div>
You can use onchange function and then submit the form
<input style="padding-left:20px; color:#4d4d4d" type="file" id="file" name="user_image" accept="image/*" />
document.getElementById("file").onchange = function() {
document.getElementById("image_upload_form").submit();
};
Related
I am trying to add multiple div tags within a form using JQuery:
Below is my initial HTML form:
<form action="" method="post">
<div id="div_file0">
<input type="file" name="files0[]" id="files0" multiple><br/>
</div>
<a href="#" id='more_files'>Click to add more files</a>
After uploading multiple files, click Submit.<br>
<input type="submit" value="Submit">
</form>
Upon clicking on Click to add more files, I want more div tags to be created as below:
<form action="http://localhost:5000/api/upload_file" method="post">
<div id="div_file0">
<input type="file" name="files0[]" id="files0" multiple=""><br>
</div>
<div id="div_file1">
<input type="file" multiple="" id="files1" name="files1[]"><a class="remove" href="#" id="remove_file" name="remove_file1" value="1">Remove file</a>
</div>
Click to add more files
After uploading multiple files, click Submit.<br>
<input type="submit" value="Submit">
</form>
However, the new div tag replaces the existing content, and adds the new and old input tags within newly created div element.
<form action="http://localhost:5000/api/upload_file" method="post">
<div id="div_file1">
<input type="file" name="files0[]" id="files0" multiple=""><br>
<input type="file" multiple="" id="files1" name="files1[]"><a class="remove" href="#" id="remove_file" name="remove_file1" value="1">Remove file</a>
</div>
Click to add more files
After uploading multiple files, click Submit.<br>
<input type="submit" value="Submit">
</form>
Javascript used is as below:
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click','#more_files', function() {
var numOfInputs = 1;
while($('#files'+numOfInputs).length) { numOfInputs++; }//once this loop breaks, numOfInputs is greater than the # of browse buttons
console.log("numOfInputs:"+numOfInputs)
$("<br/>").insertAfter("#div_file"+(numOfInputs-1));
$("div")
.attr("id","div_file"+numOfInputs)
.insertAfter("#div_file"+(numOfInputs-1));
var input = $("<input type='file' multiple/>")
.attr("id", "files"+numOfInputs)
.attr("name", "files"+numOfInputs+"[]");
var remove = $("<a class='remove' href='#'>Remove file</a>")
.attr("id","remove_file")
.attr("name","remove_file"+numOfInputs)
.attr("value",numOfInputs);
$("#div_file"+numOfInputs).append(input,remove);
});
});
</script>
This rather redundant as you're using a multiple file input already.
If you really want to do it in this manner, then remove all id attributes from the HTML content you're going to repeat in the DOM. They aren't necessary and just create more needless complication. Then you can grab the first .div_file element, clone it, and insert it before the a in the form, like this:
$(document).ready(function() {
$(document).on('click', '#more_files', function() {
var $clone = $('.div_file:first').clone();
$clone.insertBefore('form a');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post">
<div class="div_file">
<input type="file" name="files[]" multiple><br/>
</div>
<a href="#" id='more_files'>Click to add more files</a> After uploading multiple files, click Submit.<br>
<input type="submit" value="Submit">
</form>
My goal is to automatically upload an image to a folder when the file is selected. Following the answer on how do I auto-submit an upload form when a file is selected, I attempted to use Javascript's onchange event to automatically submit the form:
<?php
if(isset($_POST['upload']))
{
$ImageName = $_FILES['photo']['name'];
$fileElementName = 'photo';
$path = '../images/';
$location = $path . $_FILES['photo']['name'];
move_uploaded_file($_FILES['photo']['tmp_name'], $location);
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="photo" onchange="document.getElementById('upload').submit();" id="file" class="inputfile" />
<label for="file">Add Image</label>
<input type="submit" style="display: none;" name="upload" id="upload">
<input type="text">
<input type="submit">
</form>
When the file is selected, it's not automatically uploaded to a folder.
Note: I cannot use onchange="form.submit()" as I have multiple submit buttons in my form!
I think you could simply change it to:
document.getElementById('upload').click();
Or do something like this:
var button = document.getElementById('upload');
button.form.submit();
Sorry if this question is a bit confusing but I don't know how else i can explain it so please bear with me.
Basically, I need to use 1 button for choose file and once the file's chosen, the file gets uploaded automatically as opposed to the standard file input + submit button if that makes sense?
So the usual standard file upload is like this:
<form id="form" action="ajaxupload.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" />
<input id="button" type="submit" value="Upload">
</form>
is there any way so we can have something like this:
<form id="form" action="ajaxupload.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" />
</form>
and once the file's chosen from that dialog box that opens after clicking on the choose file (file input), the file gets uploaded?
I've seen this done on many sites and I just wonder how they do it.
Any help would be appreciated.
The below code should help you fix it
$("document").ready(function() {
$("#uploadImage").change(function() {
$('#form').submit();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" action="ajaxupload.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" />
</form>
Best way to do this with preview:
<input type='file' />
<img id="myImg" src="#" alt="your image" />
$("#myImg").hide();
$(function () {
$(":file").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$("#myImg").show();
$('#myImg').attr('src', e.target.result);
};
Codepen: http://codepen.io/anon/pen/aNqPbb
You can use this library Dropzone.js
Click the link below
http://www.dropzonejs.com/
Add a javascript change event the file input. inside the change function do your file upload
Also set the css for the #uploadImage to hidden
ie. #uploadimage{display:"none"}
eg in jquery
$( "#fileinput" ).change(function() {
//do the fileupload here
});
Hope this helps.
If you are using Bootstrap, you can create beautiful single button file inputs by using the Bootstrap Filestyle plugin.
This is one of the many effects you can create:
$(document).ready(function(){
// <script type="text/javascript" src="js/bootstrap-filestyle.min.js"> </script> include this file..
(function($){var nextId=0;var Filestyle=function(element,options){this.options=options;this.$elementFilestyle=[];this.$element=$(element)};Filestyle.prototype={clear:function(){this.$element.val("");this.$elementFilestyle.find(":text").val("");this.$elementFilestyle.find(".badge").remove()},destroy:function(){this.$element.removeAttr("style").removeData("filestyle");this.$elementFilestyle.remove()},disabled:function(value){if(value===true){if(!this.options.disabled){this.$element.attr("disabled","true");this.$elementFilestyle.find("label").attr("disabled","true");this.options.disabled=true}}else{if(value===false){if(this.options.disabled){this.$element.removeAttr("disabled");this.$elementFilestyle.find("label").removeAttr("disabled");this.options.disabled=false}}else{return this.options.disabled}}},buttonBefore:function(value){if(value===true){if(!this.options.buttonBefore){this.options.buttonBefore=true;if(this.options.input){this.$elementFilestyle.remove();this.constructor();this.pushNameFiles()}}}else{if(value===false){if(this.options.buttonBefore){this.options.buttonBefore=false;if(this.options.input){this.$elementFilestyle.remove();this.constructor();this.pushNameFiles()}}}else{return this.options.buttonBefore}}},icon:function(value){if(value===true){if(!this.options.icon){this.options.icon=true;this.$elementFilestyle.find("label").prepend(this.htmlIcon())}}else{if(value===false){if(this.options.icon){this.options.icon=false;this.$elementFilestyle.find(".icon-span-filestyle").remove()}}else{return this.options.icon}}},input:function(value){if(value===true){if(!this.options.input){this.options.input=true;if(this.options.buttonBefore){this.$elementFilestyle.append(this.htmlInput())}else{this.$elementFilestyle.prepend(this.htmlInput())}this.$elementFilestyle.find(".badge").remove();this.pushNameFiles();this.$elementFilestyle.find(".group-span-filestyle").addClass("input-group-btn")}}else{if(value===false){if(this.options.input){this.options.input=false;this.$elementFilestyle.find(":text").remove();var files=this.pushNameFiles();if(files.length>0&&this.options.badge){this.$elementFilestyle.find("label").append(' <span class="badge">'+files.length+"</span>")}this.$elementFilestyle.find(".group-span-filestyle").removeClass("input-group-btn")}}else{return this.options.input}}},size:function(value){if(value!==undefined){var btn=this.$elementFilestyle.find("label"),input=this.$elementFilestyle.find("input");btn.removeClass("btn-lg btn-sm");input.removeClass("input-lg input-sm");if(value!="nr"){btn.addClass("btn-"+value);input.addClass("input-"+value)}}else{return this.options.size}},placeholder:function(value){if(value!==undefined){this.options.placeholder=value;this.$elementFilestyle.find("input").attr("placeholder",value)}else{return this.options.placeholder}},buttonText:function(value){if(value!==undefined){this.options.buttonText=value;this.$elementFilestyle.find("label .buttonText").html(this.options.buttonText)}else{return this.options.buttonText}},buttonName:function(value){if(value!==undefined){this.options.buttonName=value;this.$elementFilestyle.find("label").attr({"class":"btn "+this.options.buttonName})}else{return this.options.buttonName}},iconName:function(value){if(value!==undefined){this.$elementFilestyle.find(".icon-span-filestyle").attr({"class":"icon-span-filestyle "+this.options.iconName})}else{return this.options.iconName}},htmlIcon:function(){if(this.options.icon){return'<span class="icon-span-filestyle '+this.options.iconName+'"></span> '}else{return""}},htmlInput:function(){if(this.options.input){return'<input type="text" class="form-control '+(this.options.size=="nr"?"":"input-"+this.options.size)+'" placeholder="'+this.options.placeholder+'" disabled> '}else{return""}},pushNameFiles:function(){var content="",files=[];if(this.$element[0].files===undefined){files[0]={name:this.$element[0]&&this.$element[0].value}}else{files=this.$element[0].files}for(var i=0;i<files.length;i++){content+=files[i].name.split("\\").pop()+", "}if(content!==""){this.$elementFilestyle.find(":text").val(content.replace(/\, $/g,""))}else{this.$elementFilestyle.find(":text").val("")}return files},constructor:function(){var _self=this,html="",id=_self.$element.attr("id"),files=[],btn="",$label;if(id===""||!id){id="filestyle-"+nextId;_self.$element.attr({id:id});nextId++}btn='<span class="group-span-filestyle '+(_self.options.input?"input-group-btn":"")+'"><label for="'+id+'" class="btn '+_self.options.buttonName+" "+(_self.options.size=="nr"?"":"btn-"+_self.options.size)+'" '+(_self.options.disabled?'disabled="true"':"")+">"+_self.htmlIcon()+'<span class="buttonText">'+_self.options.buttonText+"</span></label></span>";html=_self.options.buttonBefore?btn+_self.htmlInput():_self.htmlInput()+btn;_self.$elementFilestyle=$('<div class="bootstrap-filestyle input-group">'+html+"</div>");_self.$elementFilestyle.find(".group-span-filestyle").attr("tabindex","0").keypress(function(e){if(e.keyCode===13||e.charCode===32){_self.$elementFilestyle.find("label").click();return false}});_self.$element.css({position:"absolute",clip:"rect(0px 0px 0px 0px)"}).attr("tabindex","-1").after(_self.$elementFilestyle);if(_self.options.disabled){_self.$element.attr("disabled","true")}_self.$element.change(function(){var files=_self.pushNameFiles();if(_self.options.input==false&&_self.options.badge){if(_self.$elementFilestyle.find(".badge").length==0){_self.$elementFilestyle.find("label").append(' <span class="badge">'+files.length+"</span>")}else{if(files.length==0){_self.$elementFilestyle.find(".badge").remove()}else{_self.$elementFilestyle.find(".badge").html(files.length)}}}else{_self.$elementFilestyle.find(".badge").remove()}});if(window.navigator.userAgent.search(/firefox/i)>-1){_self.$elementFilestyle.find("label").click(function(){_self.$element.click();return false})}}};var old=$.fn.filestyle;$.fn.filestyle=function(option,value){var get="",element=this.each(function(){if($(this).attr("type")==="file"){var $this=$(this),data=$this.data("filestyle"),options=$.extend({},$.fn.filestyle.defaults,option,typeof option==="object"&&option);if(!data){$this.data("filestyle",(data=new Filestyle(this,options)));data.constructor()}if(typeof option==="string"){get=data[option](value)}}});if(typeof get!==undefined){return get}else{return element}};$.fn.filestyle.defaults={buttonText:"Choose file",iconName:"glyphicon glyphicon-folder-open",buttonName:"btn-default",size:"nr",input:true,badge:true,icon:true,buttonBefore:false,disabled:false,placeholder:""};$.fn.filestyle.noConflict=function(){$.fn.filestyle=old;return this};$(function(){$(".filestyle").each(function(){var $this=$(this),options={input:$this.attr("data-input")==="false"?false:true,icon:$this.attr("data-icon")==="false"?false:true,buttonBefore:$this.attr("data-buttonBefore")==="true"?true:false,disabled:$this.attr("data-disabled")==="true"?true:false,size:$this.attr("data-size"),buttonText:$this.attr("data-buttonText"),buttonName:$this.attr("data-buttonName"),iconName:$this.attr("data-iconName"),badge:$this.attr("data-badge")==="false"?false:true,placeholder:$this.attr("data-placeholder")};$this.filestyle(options)})})})(window.jQuery);
$(":file").filestyle({input: false});
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<input type="file" class="filestyle" data-input="false" data-buttonName="btn-info btn-xs" />
I have multiple forms in my php file for different buttons. So, if I click on Back button, ramesh.php script should be called and so on. This is the code.
<form action="ramesh.php">
<input type="submit" value="Back" />
</form>
<form action="process.php" method="post">
<input name="rep_skyline" type="text" />
<input type="submit" />
</form>
<form action="update.php" method="post" >
<button type="submit">Update</button>
</form>
However, I need to pass some data to server from my client side on form submit just for the update button. I have a javascript function to send the data to server side as below.
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function(e) {
var mydata = 3;
if ($(this).is(':not([data-submit="true"])'))
{
$('form').append('<input type="hidden" name="foo" value="'+mydata+'">');
$('form').data('submit', 'true').submit();
e.preventDefault();
return false;
}
})
})
</script>
If I click on the update button, the javascript function is working fine. However, if I click on Back or Submit button, I should not be calling the javascript function. Is there someway to do this?
Give your form an id:
<form action="update.php" method="post" id="update-form">
Then use a more specific selector:
$("#update-form").submit(function() {
// Code
});
I'm not quite sure why you need JavaScript to dynamically add data to your form, however. You should just use an <input type="hidden" /> directly.
type=submit will always load the form's action. Try to specify wich form to submit.
<form name="backForm" id="backForm" action="ramesh.php">
<input type="submit" value="Back" />
</form>
<form name="form2" id="form2" action="process.php" method="post">
<input name="rep_skyline" type="text" />
<input type="submit" />
</form>
Now you can access the form via document.backForm or document.getElementById("backForm") and than use submit(); like document.getElementById("backForm").submit();
I'm pretty new to jQuery and I'm trying to make simple HTML upload page and I want to add new file input to form after selecting some file. I've tried this code
<form id="upload" action="upload.php" method="POST" enctype="multipart/form-data" onchange="addField();">
<label for="file">Soubor:</label>
<input type="file" name="files[]" id="file" /><br />
<input type="submit" name="Odeslat" value="Odeslat soubor" />
</form></body>
<script>
$('#upload').delegate('input[type=file]', 'change', function(){
alert('Alert');
addField();
});
</script>
and this addField() function
function addField(){
$('<input type="file" name="files[]" id="file" /><br />').insertAfter('#file');
};
But if I run this code, the 3rd input field is inserted after the 1st one instead of after the last field. Is it possible to add input fields after the last file input without using unique ids for these inputs? http://jsfiddle.net/aHrTd/
Thanks for any help.
How about this - (find last input:file in form and insert new input after it)
function addField(){
$('form input:file').last().after($('<input type="file" name="files[]" class="file" /><br />'));
}
Here is a solution: http://jsfiddle.net/aHrTd/4/
Adds a unique name and id to the new file inputs and inserts after last file input as pXL has suggested.
Note that I have used one of the most under-utilized jQuery abilities, though it easy to find (http://api.jquery.com/jQuery/) can build a new element for you in a nice clean way.
<form id="upload" action="upload.php" method="POST" enctype="multipart/form-data" onchange="addField();">
<label for="file">Soubor:</label>
<input type="file" name="files" id="file" /><br />
<input type="submit" name="Odeslat" value="Odeslat soubor" />
</form>
<script>
function addField(){
var lastfile = $('form input:file').last();
var countfile = ($('form input:file').length)+1;
$( "<input/>", {
"type": "file",
"name": "file_"+countfile,
"id": "file_"+countfile
}).insertAfter(lastfile);
fileinputmonitor();
}
function fileinputmonitor(){
$('input[type="file"]').change(function(){
alert('Alert');
addField();
});
}
fileinputmonitor();
</script>
Your inputs have to have unique ids. Give them a unique id and it should work fine.
You can use .last()
HTML
<form id="upload" action="upload.php" method="POST" enctype="multipart/form-data" onchange="addField();">
<label for="file">Soubor:</label>
<input type="file" name="files[]" id="file" class='dynamic-file' /><br />
<input type="submit" name="Odeslat" value="Odeslat soubor" />
JS
function addField(){
$('<input type="file" name="files[]" class="dynamic-file" /><br />').insertAfter($('.dynamic-file').last());
};