My task is i have added multiple browse file clicking on add more button at the same time i have to view the file also after browsing the file for this i have used below code and i have succeded to browse the file on one browse box but i was unable to view all the image simultaneously.I am not getting how to do this
my check.html file
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="custom.js" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="file_wrapper" id="file_wrapper">
<div>
<span class="btn btn-default btn-file"><i class="fa fa-upload"></i>
Select Image<input id="fileupload" class="fileupload" type="file" name="userFiles[]" required/>
</span>
<span class="btn btn-success">
<a href="javascript:void(0);" class="add_image" title="Add field">
<span class="glyphicon glyphicon-plus" >Add more</span>
</a>
</span>
</div>
</div>
<hr />
<b>Live Preview</b>
<br />
<br />
<div id="dvPreview">
</div>
my second custom.js file is
// Add More field script
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_image'); //Add button selector
var wrapper = $('.file_wrapper'); //Input field wrapper
var fieldHTML = '<div><span class="btn btn-default btn-file"><i class="fa fa-upload"></i>Select Image<input id="fileupload" class="fileupload" type="file" name="userFiles[]" required/></span> <span class="btn btn-success"><span class="glyphicon glyphicon-minus">Remove</span></span></div>';
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
$(function () {
// View Image on Browse Script
$(".fileupload").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#dvPreview");
dvPreview.html("");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("style", "height:200px;width: 300px");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
dvPreview.html("");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
});
Please help me
Thanks in Advance
every time you choose new image you remove previous one so delete first dvPreview.html("");
// Add More field script
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_image'); //Add button selector
var wrapper = $('.file_wrapper'); //Input field wrapper
var fieldHTML = '<div><span class="btn btn-default btn-file"><i class="fa fa-upload"></i>Select Image<input id="fileupload" class="fileupload" type="file" name="userFiles[]" required/></span> <span class="btn btn-success"><span class="glyphicon glyphicon-minus">Remove</span></span></div>';
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
$(function () {
// View Image on Browse Script
$(".fileupload").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#dvPreview");
//dvPreview.html("");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("style", "height:200px;width: 300px");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
//dvPreview.html("");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
});
Related
I've created a list of some movie titles. If user has permission he can edit those names by pressing crtl + left click on title that he want to be changed.
P tag changes into input and on enter key ajax request is send with new name to the backend. That works fine. But I don't have any way to cancel name edit or block user from clicking on another title when one already is beeing edited
What I was trying to do is to check if user clicked something else that isn't an input and if so change back input to P tag but this isn't working.
jsFiddle.
$(document).ready(function() {
$('.nameChanger').on("mousedown", function(e) {
e.preventDefault();
if (e.ctrlKey) {
var $textElement = $(this);
var $input = $('<input class="inputElementNew" />').val($textElement.text());
var $textValue = $textElement.text()
$textElement.replaceWith($input);
if ($(e.target).closest('.inputElementNew').length === 0) {
//var $p = $('<p class="nameChanger" />').text($textElement.text());
console.log("back to oryginal")
//$input.replaceWith($p)
}
//used so you can click once on link element and new page won't open
$('.doubleLink').click(function() {
return false;
}).dblclick(function() {
window.location = this.href;
return false;
});
var send = function() {
var $p = $('<p class="nameChanger" />').text($input.val());
$input.replaceWith($p);
//ajax request is here
};
$input.keypress(function(e) {
if (e.keyCode == 13) {
console.log("changed")
$input.one('focusout', send)
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div title="Press CRTL + left click to change name and press enter">
<a class="doubleLink" href="#"><b>
<p class="nameChanger" data-title="item-1">Movie title 1</p>
</b></a>
</div>
<div title="Press CRTL + left click to change name and press enter">
<a class="doubleLink" href="#"><b>
<p class="nameChanger" data-title="item-2">Movie title 2</p>
</b></a>
</div>
$(document).ready(function () {
function mouseDown() {
$('.nameChanger').on("mousedown", function (e) {
e.preventDefault();
if (e.ctrlKey) {
var $textElement = $(this);
var $input = $('<input class="inputElementNew" />').val($textElement.text());
var $textValue = $textElement.text()
$textElement.replaceWith($input);
$input.focus();
if ($(e.target).closest('.inputElementNew').length === 0) {
//var $p = $('<p class="nameChanger" />').text($textElement.text());
console.log("back to oryginal")
//$input.replaceWith($p)
}
//used so you can click once on link element and new page won't open
$('.doubleLink').click(function () {
return false;
}).dblclick(function () {
window.location = this.href;
return false;
});
var send = function () {
var $p = $('<p class="nameChanger" />').text($input.val());
$input.replaceWith($p);
//ajax request is here
mouseDown();
};
$(".inputElementNew").on("focusout", function () {
send();
})
$input.keypress(function (e) {
if (e.keyCode == 13) {
send();
}
});
}
});
}
mouseDown();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div title="Press CRTL + left click to change name and press enter">
<a class="doubleLink" href="#"><b>
<p class="nameChanger" data-title="item-1">Movie title 1</p>
</b></a>
</div>
<div title="Press CRTL + left click to change name and press enter">
<a class="doubleLink" href="#"><b>
<p class="nameChanger" data-title="item-2">Movie title 2</p>
</b></a>
</div>
Your p-elements elements only get the Event-bindung once on document.ready().
The new created objects don't have an event-listener.
Best Practice would be creating the inputs and the p-elements at the same time and use css to show either one or the other and update with jquery.
If you want to use your approach you have to add the eventListener ".on" again to the P elements.
Please find the updated jsfiddle, Hope this solution help.
$(document).ready(function() {
$(document).on("mousedown",".nameChanger", function(e) {
e.preventDefault();
if (e.ctrlKey) {
var data_title = $(this).attr("data-title");
var data_val = $(this).html();
$(".inputElementNew").each(function(i,e){
$(this).replaceWith('<p class="nameChanger" data-title="'+data_title+'">'+$(this).val()+'</p>');
})
var $textElement = $(this);
var $input = $('<input class="inputElementNew" data-title="'+data_title+'"/>').val($textElement.text());
var $textValue = $textElement.text()
$textElement.replaceWith($input);
if ($(e.target).closest('.inputElementNew').length === 0) {
//var $p = $('<p class="nameChanger" />').text($textElement.text());
console.log("back to oryginal")
//$input.replaceWith($p)
$input.focus();
}
//used so you can click once on link element and new page won't open
$('.doubleLink').click(function() {
return false;
}).dblclick(function() {
window.location = this.href;
return false;
});
var send = function() {
var $p = $('<p class="nameChanger" />').text($input.val());
$input.replaceWith($p);
//ajax request is here
};
$input.keypress(function(e) {
if (e.keyCode == 13) {
console.log("changed")
$input.one('focusout', send)
}
});
$(".inputElementNew").on("focusout",function(){
$(this).replaceWith('<p class="nameChanger" data-title="'+data_title+'">'+$(this).val()+'</p>');
})
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div title="Press CRTL + left click to change name and press enter">
<a class="doubleLink" href="#"><b>
<p class="nameChanger" data-title="item-1">Movie title 1</p>
</b></a>
</div>
<div title="Press CRTL + left click to change name and press enter">
<a class="doubleLink" href="#"><b>
<p class="nameChanger" data-title="item-2">Movie title 2</p>
</b></a>
</div>
I have jQuery code that executes an AJAX request every time the text input is focused out. The thing I don't understand is when I focus back in the AJAX request gets executed. There's no focusin function defined. Code snippet below:
$(function() {
// some other functions here but no focusin function defined.
$( "#additem" ).click(function(e) {
e.preventDefault();
var _id = "new_pn", _holder = "Enter part number here", btnId = "post", btnIcon = "fa fa-save", btnText = " Add Serial", formId = "new-sn";
openModal(_id, _holder, btnId, btnIcon, btnText, formId);
});
var openModal = function(a,b,c,d,e, f) {
var txtInput = $("#myModal form input")[1], btn = $("#myModal form button")[0], icon = $("#myModal form i")[0], form = $("#myModal form")[0];
txtInput.id = a;
txtInput.placeholder = b;
btn.id = c;
icon.className = d;
form.id = f;
$($("#myModal form span")[1]).text(e);
$("#myModal").attr('style', 'display:block');
};
//Check serial before saving when text field is focusout. 2nd argument, #new-sn is a dynamically created form id.
$('#myModal').on('focusout', $('#new-sn input')[0], function() {
var sn = $("#serial").val();
if (sn) {
Promise.resolve(GetDocumentItems(serialsDb, sn)).then(function() {
console.log(sn.toUpperCase() + " already exists in the database");
}).catch(function() {
console.log(sn.toUpperCase() + " is cleared to save in database.");
});
}
});
});
What am I doing wrong here? Cheers
Added HTML code below:
<div id="myModal" class="modal">
<div class="modal-content">
<!--variable form id (depends on the caller)-->
<form>
<div class="container">
<span class="close">×</span>
<input id="serial" type="text" placeholder="Enter serial number here">
<!--2nd text box, variable id and placeholder (depends on the caller)-->
<input type="text">
<!--button variable id and i variable class (invoker dependent).-->
<button class="green"><i></i> <span></span></button>
</div>
</form>
</div>
</div>
I have found a code on internet to upload multiple images. While you select the image, it will show the selected image just below as preview, now the problem is what if I selected the wrong image and I want to remove that particular image, also no more than 4 image should be allowed
hope you get what I want to say below is the code
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
and jquery for the code is
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
The file list of HTML5 file input is readonly. So it's not possible to remove a single file out from a multiple file selection.
It's perfectly fine to empty a file input by resetting the form. You just can't modify it. So if you use 4 seperate single file selections, it's a simple matter of clearing the one that's being removed by the user:
HTML:
<form>
<input type="file" name='images[]' class="gallery-photo-add" id='image1' />
<input type="file" name='images[]' class="gallery-photo-add" id='image2' />
<input type="file" name='images[]' class="gallery-photo-add" id='image3' />
<input type="file" name='images[]' class="gallery-photo-add" id='image4' />
</form>
<div class="gallery"></div>
JS:
$(function() {
// Multiple images preview in browser
var imagesPreview = function(placeToInsertImagePreview) {
// Empty preview so we can safely rebuild it
$(placeToInsertImagePreview).empty();
// Get all files
var elems = document.getElementsByClassName("gallery-photo-add");
// Loop through each file and append them to the preview if available
for (i = 0; i < elems.length; i++) {
if (elems[i].files.length != 0) {
var reader = new FileReader();
var id = $(elems[i]).attr('id');
reader.onload = (function(id) {
return function(e){
$($.parseHTML('<img>')).attr({
'src' : e.target.result,
'data-id' : id
}).appendTo(placeToInsertImagePreview);
}
})(id);
reader.readAsDataURL(elems[i].files[0]);
}
}
};
// Temporarely wrap a form element around the input to reset it
window.reset = function(e) {
e.wrap("<form>").closest('form').get(0).reset();
e.unwrap();
}
$('div.gallery').on('click', 'img', function() {
var id = $(this).attr("data-id");
reset($('#'+id));
$(this).remove();
});
$('.gallery-photo-add').on('change', function() {
imagesPreview('div.gallery');
});
});
You can test it here: https://jsfiddle.net/81nytqsc/2/
$('div.gallery').on('click','img',function(){
var files= $('#gallery-photo-add).get(0).files;
for(i=0;i<files.length;i++){
if(files[i]==$(this).attr('src')){
files= jQuery.grep(files, function(value) {
return value != files[i];
}
}
}
$(this).remove();
});
I have reference for using ;nbsp in javascript from in script is not getting compiled but It still couldn't work for me.
$(document).ready(function(){
var addButtonn = $('.add_rescuer'); //Add button selector
var wrapperr = $('.field_rescuer'); //Input field wrapper
var fieldHTMLL = '<div data-role="dynamic-fields"><div class="form-inline"><div class="form-group" id="txtboxToFilter"><label for="instansi"><font color="white">Instansi yang Terlibat:</font></label> \u00A0\u00A0\u00A0 <input type="text" class="form-control" name="rescuer[]" placeholder="Masukkan Kegiatan" required size="92"/></div> <i class="fa fa-fw fa-minus"></i></div></div></div>'; //New input field html
var y = 1; //Initial field counter is 1
$(addButtonn).click(function(){ //Once add button is clicked
y++; //Increment field counter
$(wrapperr).append(fieldHTMLL); // Add field html
});
$(wrapperr).on('click', '.remove_rescuer', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').parent('div').remove(); //Remove field html
y--; //Decrement field counter
});
});
When I tried to running that code, it was not changing anything. What is the problem ? \u00A0 has not worked properly.
In that font color is the problem, i think it's in white color:
for your reference
https://codepen.io/kalaiselvan/pen/ybWxxW
$(document).ready(function(){
var addButtonn = $('.add_rescuer'); //Add button selector
var wrapperr = $('.field_rescuer'); //Input field wrapper
var fieldHTMLL = '<div data-role="dynamic-fields"><div class="form-inline"><div class="form-group" id="txtboxToFilter"><label for="instansi"><font color="black">Instansi yang Terlibat:</font></label> \u00A0\u00A0\u00A0 <input type="text" class="form-control" name="rescuer[]" placeholder="Masukkan Kegiatan" required size="92"/></div> <i class="fa fa-fw fa-minus"></i></div></div></div>'; //New input field html
var y = 1; //Initial field counter is 1
$(addButtonn).click(function(){ //Once add button is clicked
y++; //Increment field counter
$(wrapperr).append(fieldHTMLL); // Add field html
});
$(wrapperr).on('click', '.remove_rescuer', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').parent('div').remove(); //Remove field html
y--; //Decrement field counter
});
});
given this html snippet
<div id="imageSelection" class="form-group">
#Html.LabelFor(m => m.PostedFiles,"Select images/videos" ,new {id="fileSelect",#for="fileElem", #class="form-control btn btn-sm btn-success", style="width:144px;" })
#Html.TextBoxFor(m => m.PostedFiles, new
{
type = "file",
id = "fileElem",
#class = "col-md-10 form-control",
style="display:none;",
multiple = "multiple",
accept = "image/*",
onchange = "handleFiles(this.files)"
})
</div>
which works fine, you click the button, the file picker opens, you select some files and click the button to close the file picker. The onchange event is not firing (onchange is the event suggested by the example here)
It generates this html in the page
<div id="imageSelection" class="form-group">
<label class="form-control btn btn-sm btn-success" for="fileElem" id="fileSelect" style="width:144px;">Select images/videos</label>
<input accept="image/*" class="col-md-10 form-control" id="fileElem" multiple="multiple" name="PostedFiles" onchange="handleFiles(this.files)" style="display:none;" type="file" value="" />
</div>
Here is the script
<script>
$(document)
.ready(function () {
//element variables for the thumbnail display
var dropbox = $("#dropbox"),
filePropertyDisplay = $("#loadingImageFileProperties"),
fileName = $("#dd_filename"),
fileSize = $("#dd_filesize"),
fileType = $("#dd_filetype"),
gallery = $("#imageGallery"),
uploading = $("#imageUploading"),
fileSelect = document.getElementById("fileSelect"), //$("#fileSelect"),
fileElem = document.getElementById("fileElem"), //$("#fileElem"),
messages = $("#messageArea");
gallery.hide();
uploading.hide();
//add event listeners to handle events
dropbox.on("dragenter", function(e) {
e.stopPropagation();
e.preventDefault();
});
dropbox.on("dragover", function (e) {
e.stopPropagation();
e.preventDefault();
});
dropbox.on("drop", function (e) {
e.stopPropagation();
e.preventDefault();
var dt = e.originalEvent.dataTransfer;
var files = dt.files;
handleFiles(files);
});
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
//fileSelect.on("click", function (e) {
// if (fileElem) {
// fileElem.click();
// }
// // prevent navigation to "#"
// e.preventDefault();
//});
function handleFiles(files) {
alert(files.length);
}
});
</script>
I originally was trying to stick with JQuery but couldn't get that to work with .on() either, so i reverted back to Javascript, per the example, but that doesn't work either.
The drop functionality works, and calls handleFiles but the fileElem onchange method doesn't fire.
EDIT:
Sorry that made me realize that the problem was reading the files you've selected instead of just getting the code to work.
I've just added:
var files = $(this)[0].files;
To get the files collection the user selected (it could be one or more);
and then:
for (var i = 0; i < files.length; i++) {
alert(files[i].name);
}
loop through all the files selected and just get the name of it. You can also read .size if you need to.
This will the proper way to handle what you are trying to achieve.
$(document)
.ready(function () {
//element variables for the thumbnail display
var dropbox = $("#dropbox"),
filePropertyDisplay = $("#loadingImageFileProperties"),
fileName = $("#dd_filename"),
fileSize = $("#dd_filesize"),
fileType = $("#dd_filetype"),
gallery = $("#imageGallery"),
uploading = $("#imageUploading"),
fileSelect = document.getElementById("fileSelect"), //$("#fileSelect"),
fileElem = document.getElementById("fileElem"), //$("#fileElem"),
messages = $("#messageArea");
gallery.hide();
uploading.hide();
//add event listeners to handle events
dropbox.on("dragenter", function(e) {
e.stopPropagation();
e.preventDefault();
});
dropbox.on("dragover", function (e) {
e.stopPropagation();
e.preventDefault();
});
dropbox.on("drop", function (e) {
e.stopPropagation();
e.preventDefault();
var dt = e.originalEvent.dataTransfer;
var files = dt.files;
handleFiles(files);
});
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
$('#fileElem').on('change',function(e){
var files = $(this)[0].files;
for (var i = 0; i < files.length; i++) {
alert(files[i].name);
//alert(files[i].size);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imageSelection" class="form-group">
<label for="fileElem" class="form-control btn btn-sm btn-success", style="width:144px;" id="fileSelect">Select images/videos</label>
<input type="file" id = "fileElem" class = "col-md-10 form-control"
style="display:none;"
multiple = "multiple"
accept = "image/*"
</div>