How to preview dynamically uploaded images before upload? - javascript

I am trying to understand why I can't preview multiple images that are in different divs.
I am appending a new div that includes a new input for a file upload, sort of a section for a set of instructions, each has it's own image.
When I try uploading, the preview only works for the first div, not the rest. I thought the on event handler would work, but it does not.
$('.instructions__add-new').on('click', function() {
$('.instructions__append-inputs').append('<div class="instructions__container"><img id="instructionsImg" src=""><input type="file" class="instructions__image-input" name="recipe_instructions_image[]" onchange="document.getElementById("instructionsImg").src = window.URL.createObjectURL(this.files[0])"></div><div class="instructions__append-inputs"></div>');
});
#instructionsImg {
width: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="instructions__container">
<img id="instructionsImg" src="">
<input type="file" class="instructions__image-input" name="recipe_instructions_image[]" onchange="document.getElementById('instructionsImg').src = window.URL.createObjectURL(this.files[0])">
</div>
<div class="instructions__append-inputs"></div>
<div class="instructions__add-new">+ New Instruction</div>

If you make a small change, it will work. Instead of find it using previousSibling selector in javascript.
https://jsfiddle.net/e4wez2d1/1/
$('.instructions__add-new').on('click', function() {
$('.instructions__append-inputs').append('<div class="instructions__container"><img id="instructionsImg" src=""><input type="file" class="instructions__image-input" name="recipe_instructions_image[]" onchange="this.previousSibling.src = window.URL.createObjectURL(this.files[0])"></div><div class="instructions__append-inputs"></div>');
});

In your JQuery script, check your quotes in your string.
onchange = " document ( " quote error " ) "
Use antislash quotes. Like \"

From your code, i think you should use the event of jquery for input changing.
$('input.instructions__image-input').on('change',function(){
var divParent = $(this).closest("div.instructions__container");
$("#instructionsImg",divParent).attr("src",window.URL.createObjectURL(this.files[0])) ;
});

Related

select and remove multiple images with preview before upload

I'm looking for a plugin which allows adding multiple images, previewing, removing and submitting with some extra fields without ajax.
i have found some very good plugins like fineUploader and dropzone but they submit with ajax. with these plugins i haven't figured out how to submit without ajax.
I'm looking for a plugin which allows adding multiple images, previewing, removing and submitting with some extra fields without
ajax.
multiple images ----> <input type='file' id="myfiles" multiple="multiple" name="files[]">
previewing ---> Jquery
removing-----> Highly impossible to remove one by one image from file list,as the api is read only,however we can clear the entire file list, when the remove button is clicked.
without ajax ----> Just action the form to the controller/handler.
I don't think there's a way to achieve what you need beside using one of the plugins you have mentioned above.
You have 2 Options that I can think of currently.
use the multiple attribute on the file input type, then u can be able to use jquery to preview the images that are loaded but however we can not remove the image one by one from the filelist we can only remove the image from the preview but the server side still gonna process the image, or we can just clear the entire filelist, as I have mentioned above.
OR
we can add the file field dynamically using jquery, in this way we can be able to add one image add a time, then have an add more images button that will append a new file input to our form, with this we will be able to remove images one by one before processing in the server side.
Option 1
$('document').ready(function() {
var images = function(input, imgPreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML("<img class='pic'>")).attr('src', event.target.result).appendTo(imgPreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#myimg').on('change', function() {
images(this, '#previews');
});
//clear the file list when image is clicked
$('body').on('click','img',function(){
$('#myimg').val("");
$('#previews').html("");
});
});
img{
cursor: pointer;
}
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<form id="form1" enctype="multipart/form-data" action="server.php" method="post">
<input type='file' id="myimg" multiple="multiple">
<div id="previews"></div>
<p> </p>
<button type="submit">Submit</button>
</form>
Option 2
var abc = 0;
$('#add_more').click(function ()
{
$(this).before($("<div/>",{id: 'filediv'}).fadeIn('slow').append($("<input/>",
{
name: 'file[]',
type: 'file',
id: 'file'
}),
$("<br/><br/>")
));
});
$('body').on('change', '#file', function ()
{
if (this.files && this.files[0])
{
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this)
.parent()
.find('#previewimg' + z).remove();
$(this).before("<div id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this)
.hide();
$("#abcd" + abc).append($("<img/>",{
id: 'img',
src: 'x.png', //the remove icon
alt: 'delete'
}) .click(function ()
{
$(this)
.parent()
.parent()
.remove();
}));
}
});
//image preview
function imageIsLoaded(e)
{
$('#previewimg' + abc)
.attr('src', e.target.result);
};
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<form method="POST" action="server.php" enctype="multipart/form-data">
<div class="col-md-3 col-sm-3 col-xs-3">
<div id="filediv"><input name="file[]" type="file" id="file"/></div>
<input type="button" id="add_more" class="btn btn-primary" value="Add More Files"/><br><br>
<button type="submit" class="btn btn-success">Submit</button>
</form>
I believe this more esp option 2 can do the trick, select image, add more preview delete, then when u are happy hit the submit button then do your processing on the server. You might add styling to the preview images
Goodluck.
You can use DropzoneJS
They have a list of configurable options that you can find here. Dropzone JS Usage.
If you still need more customization then you will have to add your own code to it. Hope this helps you from writing thousand lines of code.
Without AJAX requests:
This may help you. Click here!

Get the value of an <input type="text"> that was created dynamically inside a modal

i would like to get the value of an <input type="text"> that was created dynamically inside a modal and put it into variable "newcomment".
This is how i make the input:
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text'id='comment_text' value='Comment'"+"onblur=newcomment=$('#comment_text').val()"+" onfocus=if(this.value==this.defaultValue)this.value=''>"+"</input>");
$("div.modal-body").append(p);
The problem is when i write something like "ok" inside the textbox in the modal, and after i focusout from the textbox: newcomment seems not update to "ok" and still have the default "Comment" value.
1st: You need to use newcomment=this.value instead of newcomment=$('#comment_text').val()
2nd: No need to add + signs in your input html code while you not trying to concatenate string by putting variables to it
var newcomment;
var p = $("<p>");
p.append("Some text");
p.append("</p>");
p.append("<input type='text' id='comment_text' value='Comment' onblur='newcomment=this.value; alert(newcomment);' onfocus=if(this.value==this.defaultValue)this.value='' />");
$("body").append(p);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Not really the answer here, but might help you get at the root of the problem.
JS:
var newComment, defaultValue;
function doOnBlur(){
newComment = $('#comment_text').val()
}
function doOnFocus(){
if($('#comment_text').val() == defaultValue){
$('#comment_text').val('')
}
}
HTML:
<input type='text' id='comment_text' placeholder='Comment' onblur='doOnBlur()' onfocus='doOnFocus()' />
<!-- inputs dont have a close tag, also should use placeholder for temporary text -->
from here, you can set breakpoints in the debugger and see where your code is going wrong. You can also modify the functions much more easily rather than writing the executing code in the HTML

JQuery - Append to text area that has been modified with Jquery

I am trying to append the value of a div or a input box to my text area. I have this working no problem but if i clear the contents of the text area first with a Jquery action it doesnt allow me to use my append features.
E.g.
<script type="text/javascript">
$(document).ready(function() {
$("#Column1").click(function () {
$("#sql").append($("#Column1").val())
})
$("#Column2").click(function () {
$("#sql").append($("#Column2").html())
})
$("#reset_sql").click(function () {
$("#sql").val('SELECT ')
})
</script>
<div> <input type="checkbox" name="column1" id="column1" value="`Column1`"> column1 </div>
<div id="Column2"> Column2 </div>
<textarea rows="10" cols="80" name="sql" id="sql"><? echo $sql ;?></textarea>
<input type="submit" value="submit" />
<input type="button" value="reset sql" id="reset_sql" />
The input and div lines above are just generic examples but relate exactly to what i'm trying to do.
I dont understand that when i clear the text area with javascript that my appends wont work. I get no JS errors in firefox error console.
thank you
You have several issues with your code: you haven't closed your document.ready callback, you are using the incorrect case when refering to your ID's, and you're using some of the jQuery methods incorrectly. For example, append() appends HTML to an element, whereas you want to update the value.
Your logic isn't quite correct either, since columns won't be removed when you uncheck a checkbox, and the columns won't be comma delimited (it looks like you are building a SQL string here).
I believe something like this is what you're looking for:
$(document).ready(function() {
var $sql = $('#sql');
var initialValue = $sql.val();
$("#column1, #column2").on('change', function () {
var cols = [];
var checked = $('input[type="checkbox"]').filter(':checked').each(function() {
cols.push($(this).val());
});
$sql.val(initialValue + ' ' + cols.join(', '));
})
$("#reset_sql").on('click', function () {
$sql.val(initialValue)
})
});
Working Demo
Your checkbox has an id of 'column1', but your event handler is $("#Column1").click(function () {.
Case matters! Either change the id to 'Column1' or the event handler to look for $('#column1').
Demo

jQuery change image src based on data attribute

I have a list of dynamically generated divs all with unique data-id's and several image icons contained within. When an Icon is clicked a box pops up allowing a selection dependent on the action chosen. This updates the database via ajax.
I need the first icon to change when the ajax reauest returns 3.
var ls="<div class='list_body'>
<div class='lister1'>
<img src='"+path+stat1+"' data-icon_no='1' data-status='"+split_stats[0]+"' data-job_id='"+split_stats[18]+"' />
<img src='"+path+stat2+"' data-icon_no='2' data-status='"+split_stats[1]+"' data-job_id='"+split_stats[18]+"' />
<img src='"+path+stat3+"' data-icon_no='3' data-status='"+split_stats[2]+"' data-job_id='"+split_stats[18]+"' />
<img src='"+path+stat4+"' data-icon_no='4' data-status='"+split_stats[3]+"' data-job_id='"+split_stats[18]+"' />
<img src='"+path+stat5+"' data-icon_no='5' data-status='"+split_stats[4]+"' data-job_id='"+split_stats[18]+"' />
<img src='"+path+stat6+"' data-icon_no='6' data-status='"+split_stats[5]+"' data-job_id='"+split_stats[18]+"' />
</div>
<div class='lister'>"+split_stats[6]+" "+split_stats[7]+" "+split_stats[8]+"<br />["+split_stats[13]+"]"+"</div>
<div class='lister'>"+split_stats[14]+"</div>
<div class='lister'><a href='javascript:void(0);' class='lister_a'>View Appointment & Actions</a></div>
</div>";
(I have tried to space the code to make it more readable but basically this is just one line of many that is appended to the document)
My jQuery so far is...
$(document).on('click', '.submit_acc', function(){
var selected=$('.conf_app').val();
var agent=$('body').data('agent_id');
if(selected==0)
{
alert("Please make a selection from the available options.");
return;
}
var reason=$('.ag_com').val();
var data="agent_id="+agent+"&selected="+selected+"&reason="+reason+"&job_id="+gl_job_id;
alert(data);
$.ajax({
type:"POST",
url:"admin_includes/conf_job.php",
data:data,
context:gl_job_id,
success:function(html){
if(html=="3")
{
//this is where I can't get it to work......
$('.lister1[data-job_id="'+gl_job_id+'"'').find('img').eq(0).src("images/icons/start_green.png");
}
}
})//end ajax
});
I am baiscally having trouble identifying the row where to change the image.
gl_job_id is a global variable that holds the job_id which is used as the identifier in data-job_id (does that make sense ??)..
Currently this is throwing an error on the selector line but obviously the syntax is totally wrong :(
Wrong selector here:
$('.lister1[data-job_id="'+gl_job_id+'"'').find('img').eq(0).src("images/icons/start_green.png");
you trying to select div by data-job_id, also remove one ' and add ]
Something like this must be:
$('.lister1 [data-job_id="'+gl_job_id+'"]').attr('src', "images/icons/start_green.png");
this code select div, then find by data-job_id and set src attribute

Multi file upload

<?php $uploadNeed=3 ; for($i=0;$i<$uploadNeed;$i++) { ?>
<div class="smWidth">
<input type="file" name="upload_file" value="" id=" " OnClick="alert("
2 ");" />
<br />
<div class="clear">
</div>
</div>
<?php } ?>
I am able to create three file upload fields, but i want to add a new input file filed only when i select a file.... it should keep on increasing.... something like Facebook style file upload where you select a file for the first field, then the next popup's...
I am actually checking for click event of browse, but it does not work...
Here is a very basic pure-JS implementation - hopefully it will give you a nudge in the right direction...
<script type="text/javascript">
// This keeps track of how many inputs there are, because each one MUST have a unique name!
var inputCounter = 1;
function inputChange() {
// This function will add a new input element, in a div, as it is in your
// original code, every time it is called. We attach it to the onchange
// event of all the inputs
// Declare local variables and increment input counter (for input names)
var newContainerDiv, newClearDiv, newInput, newBr;
inputCounter++;
// Create the new elements and set their properties
newContainerDiv = document.createElement('div');
newContainerDiv.className = 'smWidth';
newInput = document.createElement('input');
newInput.type = 'file';
newInput.name = 'upload_file_'+inputCounter;
newInput.onchange = inputChange;
newBr = document.createElement('br');
newClearDiv = document.createElement('div');
newClearDiv.className = 'clear';
// Add the new elements to the DOM
newContainerDiv.appendChild(newInput);
newContainerDiv.appendChild(newBr);
newContainerDiv.appendChild(newClearDiv);
document.getElementById('uploads_container').appendChild(newContainerDiv);
}
</script>
<!-- just create one input at first, so we don't need the PHP loop any more -->
<div id="uploads_container">
<!-- we wrap it all in an outer container div with an id, to ease the task of adding more elements -->
<div class="smWidth">
<input type="file" name="upload_file_1" onchange="inputChange();" />
<br />
<div class="clear">
</div>
</div>
</div>
Try hooking some other events to your file field. As far as I know, jQuery has a very useful event called .change()
I think that would work in your case.

Categories

Resources