As of now, I can successfully upload an image and display it in the browser and display that it has 0 likes initially.
What I'm trying to achieve is that when the user double clicks on the image, the 0 likes should become 1 likes (I know it's not grammatically correct, I just want it to function properly first before moving onto that issue).
If you look at the console logs, it indeed shows the like number switching back and forth with every double click, which's good. The bad part is I'm not sure how to display that change in the browser.
I've tried so many different ways but running out of options. What am I doing wrong and how can I fix this?
JS file:
function previewImages() {
var preview = document.createElement('div');
preview.className = "preview";
document.body.appendChild(preview);
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
var initialCountOfLikes = 0;
var zeroLikes = document.createElement('p');
var zeroLikesTextNode = document.createTextNode(initialCountOfLikes + " likes");
document.body.appendChild(zeroLikes.appendChild(zeroLikesTextNode));
preview.appendChild(image);
image.onclick = function (event) {
if (event.detail === 2 && initialCountOfLikes === 0) {
console.log("clicked twice");
initialCountOfLikes++;
console.log("initialCountOfLikes++ => " + initialCountOfLikes);
}
else if(event.detail === 2 && initialCountOfLikes === 1) {
console.log("inside second if block");
initialCountOfLikes--;
console.log("initialCountOfLikes-- => " + initialCountOfLikes);
}
document.body.appendChild(zeroLikes.appendChild(zeroLikesTextNode));
};
});
reader.readAsDataURL(file);
}
}
document.querySelector('#file-input').addEventListener("change", previewImages);
Here's my HTML:
<div id="file-input-wrapper">
<input type="file" id="file-input" name="files" style="display: none;"/>
<label for="file-input" id="LblBrowse">
Upload your photo!
</label>
</div>
console logs:
clicked twice
index.js:126 initialCountOfLikes++ => 1
index.js:130 inside second if block
index.js:132 initialCountOfLikes-- => 0
index.js:124 clicked twice
index.js:126 initialCountOfLikes++ => 1
index.js:130 inside second if block
index.js:132 initialCountOfLikes-- => 0
This works. Your event.detail is registering as one, so I changed your listener to a dblClick event and removed that from the if statement. And nodes use nodeValue instead of innerText, so corrected in solution.
window.onload = function(){
function previewImages() {
var preview = document.createElement('div');
preview.className = "preview";
document.body.appendChild(preview);
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
var initialCountOfLikes = 0;
var zeroLikes = document.createElement('p');
var zeroLikesTextNode = document.createTextNode(initialCountOfLikes + " likes");
document.body.appendChild(zeroLikes.appendChild(zeroLikesTextNode));
preview.appendChild(image);
image.ondblclick = function (event) {
if (initialCountOfLikes === 0) {
console.log("clicked twice");
initialCountOfLikes++;
console.log("initialCountOfLikes++ => " + initialCountOfLikes);
}
else if(initialCountOfLikes === 1) {
console.log("inside second if block");
initialCountOfLikes--;
console.log("initialCountOfLikes-- => " + initialCountOfLikes);
}
zeroLikesTextNode.nodeValue = initialCountOfLikes + " likes";
document.body.appendChild(zeroLikes.appendChild(zeroLikesTextNode));
};
});
reader.readAsDataURL(file);
}
}
document.querySelector('#file-input').addEventListener("change", previewImages);
}
You can start a timer, and measure the time between clicks, when the image is clicked. If the time between clicks is less than some number, then you can increase your count.
Something like the following:
firstClick = true;
let timer = new Date().getMilliseconds();
let someValue; // set this
image.onclick = function (event) {
let currentTime = new Date().getMilliseconds();
if(firstClick){
timer = new Date().getMilliseconds();
}
let difference = currentTime - timer;
if(difference >= someValue && !firstClick){
return;
}
firstClick = !firstClick;
timer = new Date().getMilliseconds();
if (event.detail === 2 && initialCountOfLikes === 0 && !firstClick) {
console.log("clicked twice");
initialCountOfLikes++;
console.log("initialCountOfLikes++ => " + initialCountOfLikes);
}
}
You can do something similar to what I'm doing below where you use a module to increment a private counter. The comments should be enough to explain what exactly is going on in the code:
//Load the existing number of likes from the server (im just using 5 as example)
const initialLikes = 5;
//Initialize a "like" counter
const likes = ((quantity) => {
//This is the count
let i = quantity;
//We return a module that allows us to increment the count or get the current count
return {
increment: () => i += 1,
quantity: () => i
}
})(initialLikes || 0);
//Store DOM elements we're accessing in variables
const captionEl = document.querySelector('#countEl');
const imgEl = document.querySelector('#puppyImg');
//Our double click handler:
const onDblClick = e => {
//Increment the count via our module, then update the count text
likes.increment();
captionEl.textContent = likes.quantity();
}
const init = () => {
//Set the initial count text on screen
captionEl.textContent = likes.quantity();
//Attach the event handler to the img
imgEl.addEventListener('dblclick', onDblClick);
};
init();
img:hover {
cursor: pointer;
}
<img id="puppyImg" src="https://s.abcnews.com/images/Lifestyle/puppy-ht-3-er-170907_4x3_992.jpg" height="160" width="190" alt="Cute puppy photo" />
<br /> Likes: <span id="countEl"></span>
Related
I have an image that I want to stay on screen for 5 seconds and then change to another image for .5 of a second and then change back to the original.
I've set the interval to change every 5 seconds but I can't seem to work out how to make it change for the according times.
Any help or direction would be greatly appeciated!
window.setInterval(function() {
var img = document.getElementById("glitch");
img.src = "2-01.svg";
}, 5000);
Try this:
const images = ["1.svg", "2.svg"]
var element = document.getElementById("glitch");
function showFirst() {
setTimeout(() => {
element.src = images[0];
showSecond()
}, 5000)
}
function showSecond() {
setTimeout(() => {
element.src = images[1];
showFirst()
}, 500)
}
showFirst()
You are always changing the image src to same "2-01.svg" every time. Please use some flag/condition to alternate the image src.
Here is what you can try ::
window.setInterval(function() {
var img = document.getElementById("glitch");
if(img.src == "2-01.svg") {
img.src = "2-00.svg"
}
else {
img.src = "2-01.svg";
}
}, 5000);
I was doing some test watching the thread.
If that can help you (this is not a clean code) :
img_to_change = document.querySelector("#glitch");
imgs = {"a":10, "b":2, "c":3}
keys = Object.keys(imgs)
run = function(i){
img_src = keys[i];
img_next_time = imgs[keys[i]];
img_to_change.src = img_src;
i = (i+1) == keys.length ? -1 : i;
setTimeout(() => {
img_to_change.src = img_src;
run(i+1);
}, img_next_time*1000)
}
run(0);
http://jsfiddle.net/pn3dyb5m/32/
I'm working with image preview before upload.
So I'm displaying the choosen files. It's working well.
But I'm stuck in a situation.
Foreach file on the "input file", the scripts tests if it's too small (smaller than 300px w:h).
If one of these files disobey this rule (must be width and height greater than 300px), the script has set an error var as true. And, after the "for" block, check if "error" is true or false.
I'm working in this scenario:
window.onload = function () {
var fileUpload2 = document.getElementById("inputFileID");
fileUpload2.onchange = function () {
var error = false;
if (typeof (FileReader) != "undefined") {
var dvPreview = document.getElementById("divToShowPreview");
dvPreview.innerHTML = "";
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
if(fileUpload2.files.length > 3) {
alert('Only 3 files allowed!');
} else {
for (var i = 0; i < fileUpload2.files.length; i++) {
var file = fileUpload2.files[i];
if (regex.test(file.name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("IMG");
img.src = e.target.result;
img.onload = function() {
console.log(this.width + " " + this.height);
if(this.width >=300 && this.height >=300 ) {
dvPreview.appendChild(img);
} else {
error = true;
}
};
};
reader.readAsDataURL(file);
} else {
alert(file.name + " is not a valid image file.");
dvPreview.innerHTML = "";
return false;
}
}
console.log(error);
}
} else {
alert("This browser does not support HTML5 FileReader.");
}
};
};
As you can see, the console.log(error) still shows FALSE!
How can I get this var set as true?
Thanks
the problem is that the img.onload functions is asynchronously executed. therefore console.log(error) is executed before or between the img.onload
this can be proven by looking at the sequence of your console.log, that look something like:
false
300 300
200 300
to solve this problem, create a variable to count how many images have been load, then count it in every img.onload. when the count of image that has been load is equal to the uploaded image count, call a function to check if error exists. for example:
function imageError(){
alert('image size to small');
}
window.onload = function () {
var fileUpload2 = document.getElementById("inputFileID");
// add variables
var imgLoaded = 0;
fileUpload2.onchange = function () {
var error = false;
if (typeof (FileReader) != "undefined") {
var dvPreview = document.getElementById("divToShowPreview");
dvPreview.innerHTML = "";
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
if(fileUpload2.files.length > 3) {
alert('Only 3 files allowed!');
} else {
for (var i = 0; i < fileUpload2.files.length; i++) {
var file = fileUpload2.files[i];
if (regex.test(file.name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("IMG");
img.src = e.target.result;
img.onload = function() {
//increase the loaded img count
imgLoaded++;
console.log(imgLoaded); // another check to show the sequence of events
console.log(this.width + " " + this.height);
if(this.width >=300 && this.height >=300 ) {
dvPreview.appendChild(img);
} else {
error = true;
}
// call imageError if all image have been loaded and there is and error
if (imgLoaded == fileUpload2.files.length){
console.log(error) // just to check
if (error){
imageError();
}
}
};
};
reader.readAsDataURL(file);
} else {
alert(file.name + " is not a valid image file.");
dvPreview.innerHTML = "";
return false;
}
}
//console.log(error); // no need for this line
}
} else {
alert("This browser does not support HTML5 FileReader.");
}
};
};
You have to break your for when you find a error, so it will not perform the next verification.
...
} else {
error = true;
break;
}
...
I'm stuck as to why I can't get an AddEventListener click event to work on a set of images that appear in a modal. I had them working before before the modal aspect was involve, but I'm not sure that the modal broke the image click event either.
Here is the function in question, which is called within a massive document.addEventListener("DOMContentLoaded", function (event) function:
var attachClick = function () {
Array.prototype.forEach.call(containers, function (n, i) {
n.addEventListener('click', function (e) {
// populate
cleanDrawer();
var mediaFilterSelected = document.querySelector('.media-tags .tag-container .selected');
var selectedFilters = "";
if (mediaFilterSelected != "" && mediaFilterSelected != null) {
selectedFilters = mediaFilterSelected.innerHTML;
}
var portfolioItemName = '';
var selectedID = this.getAttribute('data-portfolio-item-id');
var data = portfolioItems.filter(function (item) {
portfolioItemName = item.name;
return item.id === selectedID;
})[0];
clientNameContainer.innerHTML = data.name;
descriptionContainer.innerHTML = data.description;
var childItems = data.child_items;
//We will group the child items by media tag and target the unique instance from each group to get the right main banner
Array.prototype.groupBy = function (prop) {
return this.reduce(function (groups, item) {
var val = item[prop];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups;
}, {});
}
var byTag = childItems.groupBy('media_tags');
if (childItems.length > 0) {
handleBannerItem(childItems[0]);
var byTagValues = Object.values(byTag);
byTagValues.forEach(function (tagValue) {
for (var t = 0; t < tagValue.length; t++) {
if (tagValue[t].media_tags == selectedFilters) {
handleBannerItem(tagValue[0]);
}
}
});
childItems.forEach(function (item, i) {
// console.log("childItems.forEach"); we get into here
var img = document.createElement('img'),
container = document.createElement('div'),
label = document.createElement('p');
container.appendChild(img);
var mediaTags = item.media_tags;
container.className = "thumb";
label.className = "childLabelInactive thumbLbl";
thumbsContainer.appendChild(container);
if (selectedFilters.length > 0 && mediaTags.length > 0) {
for (var x = 0; x < mediaTags.length; x++) {
if (mediaTags[x] == selectedFilters) {
container.className = "thumb active";
label.className = "childLabel thumbLbl";
}
}
}
else {
container.className = i == 0 ? "thumb active" : "thumb";
// console.log("no tags selected"); we get to here
}
img.src = item.thumb;
if (item.media_tags != 0 && item.media_tags != null) {
childMediaTags = item.media_tags;
childMediaTags.forEach(function (cMTag) {
varLabelTxt = document.createTextNode(cMTag);
container.appendChild(label);
label.appendChild(varLabelTxt);
});
}
//console.log("before adding click to images"); we get here
console.log(img.src);
img.addEventListener("click", function () {
console.log("thumbnail clicked"); //this is never reached
resetThumbs();
handleBannerItem(item);
container.className = "thumb active";
});
});
}
attachClick();
//open a modal to show off the portfolio pieces for the selected client
var tingleModal = document.querySelector('.tingle-modal');
drawer.className = 'drawer';
var portfolioModal = new tingle.modal({
onOpen: function() {
if(tingleModal){
tingleModal.remove();
}
console.log('modal open');
},
onClose: function() {
console.log('modal closed');
//tingleModal.remove();
}
});
e.preventDefault();
portfolioModal.open();
portfolioModal.setContent(document.querySelector('.drawer-content').innerHTML);
});
});
};
And the specific bit that I'm having trouble with:
console.log(img.src);
img.addEventListener("click", function () {
console.log("thumbnail clicked"); //this is never reached
resetThumbs();
handleBannerItem(item);
container.className = "thumb active";
});
I tried removing the e.PreventDefault() bit but that didn't solve the issue. I know the images are being created, so the img variable isn't empty. I feel like the addEventListener is setup correctly. I also tried moving that bit up just under the img.src = item.thumb line, but no luck. For Some reason, the click event just will not trigger for the images.
So if I understand correctly, you have a modal that lies above the images (it has a higher z-index)? Well in this case the clicks are not reaching the images as they will hit the modal. You can pass clicks through elements that lie above by applying the css property pointer-events: none; to the modal, but thats somehow controversial to what a modal is intended to do.
Are the images present in the modal on DOMContentLoaded? You may be able to try delegating the handling of clicks to a parent element if that's the case.
You can try the delegation approach shown here: Vanilla JavaScript Event Delegation
I have been experimenting with cute file browser (perfect for my project).
Cute File Browser
But came accross a incomaptibiliy issue. Im not getting any errors in console, but im also not getting any elements being rendered. I have switched libraries about and I think this plugin only works with jquery version 1.11.0, the version my project is using is 1.11.3.
How should I attempt to fix/update this small script?
CUTE SCRIPT:
$(function(){
var filemanager = $('.filemanager'),
breadcrumbs = $('.breadcrumbs'),
fileList = filemanager.find('.data');
// Start by fetching the file data from scan.php with an AJAX request
$.get('scan.php', function(data) {
var response = [data],
currentPath = '',
breadcrumbsUrls = [];
var folders = [],
files = [];
// This event listener monitors changes on the URL. We use it to
// capture back/forward navigation in the browser.
$(window).on('hashchange', function(){
goto(window.location.hash);
// We are triggering the event. This will execute
// this function on page load, so that we show the correct folder:
}).trigger('hashchange');
// Hiding and showing the search box
filemanager.find('.search').click(function(){
var search = $(this);
search.find('span').hide();
search.find('input[type=search]').show().focus();
});
// Listening for keyboard input on the search field.
// We are using the "input" event which detects cut and paste
// in addition to keyboard input.
filemanager.find('input').on('input', function(e){
folders = [];
files = [];
var value = this.value.trim();
if(value.length) {
filemanager.addClass('searching');
// Update the hash on every key stroke
window.location.hash = 'search=' + value.trim();
}
else {
filemanager.removeClass('searching');
window.location.hash = encodeURIComponent(currentPath);
}
}).on('keyup', function(e){
// Clicking 'ESC' button triggers focusout and cancels the search
var search = $(this);
if(e.keyCode == 27) {
search.trigger('focusout');
}
}).focusout(function(e){
// Cancel the search
var search = $(this);
if(!search.val().trim().length) {
window.location.hash = encodeURIComponent(currentPath);
search.hide();
search.parent().find('span').show();
}
});
// Clicking on folders
fileList.on('click', 'li.folders', function(e){
e.preventDefault();
var nextDir = $(this).find('a.folders').attr('href');
if(filemanager.hasClass('searching')) {
// Building the breadcrumbs
breadcrumbsUrls = generateBreadcrumbs(nextDir);
filemanager.removeClass('searching');
filemanager.find('input[type=search]').val('').hide();
filemanager.find('span').show();
}
else {
breadcrumbsUrls.push(nextDir);
}
window.location.hash = encodeURIComponent(nextDir);
currentPath = nextDir;
});
// Clicking on breadcrumbs
breadcrumbs.on('click', 'a', function(e){
e.preventDefault();
var index = breadcrumbs.find('a').index($(this)),
nextDir = breadcrumbsUrls[index];
breadcrumbsUrls.length = Number(index);
window.location.hash = encodeURIComponent(nextDir);
});
// Navigates to the given hash (path)
function goto(hash) {
hash = decodeURIComponent(hash).slice(1).split('=');
if (hash.length) {
var rendered = '';
// if hash has search in it
if (hash[0] === 'search') {
filemanager.addClass('searching');
rendered = searchData(response, hash[1].toLowerCase());
if (rendered.length) {
currentPath = hash[0];
render(rendered);
}
else {
render(rendered);
}
}
// if hash is some path
else if (hash[0].trim().length) {
rendered = searchByPath(hash[0]);
if (rendered.length) {
currentPath = hash[0];
breadcrumbsUrls = generateBreadcrumbs(hash[0]);
render(rendered);
}
else {
currentPath = hash[0];
breadcrumbsUrls = generateBreadcrumbs(hash[0]);
render(rendered);
}
}
// if there is no hash
else {
currentPath = data.path;
breadcrumbsUrls.push(data.path);
render(searchByPath(data.path));
}
}
}
// Splits a file path and turns it into clickable breadcrumbs
function generateBreadcrumbs(nextDir){
var path = nextDir.split('/').slice(0);
for(var i=1;i<path.length;i++){
path[i] = path[i-1]+ '/' +path[i];
}
return path;
}
// Locates a file by path
function searchByPath(dir) {
var path = dir.split('/'),
demo = response,
flag = 0;
for(var i=0;i<path.length;i++){
for(var j=0;j<demo.length;j++){
if(demo[j].name === path[i]){
flag = 1;
demo = demo[j].items;
break;
}
}
}
demo = flag ? demo : [];
return demo;
}
// Recursively search through the file tree
function searchData(data, searchTerms) {
data.forEach(function(d){
if(d.type === 'folder') {
searchData(d.items,searchTerms);
if(d.name.toLowerCase().match(searchTerms)) {
folders.push(d);
}
}
else if(d.type === 'file') {
if(d.name.toLowerCase().match(searchTerms)) {
files.push(d);
}
}
});
return {folders: folders, files: files};
}
// Render the HTML for the file manager
function render(data) {
var scannedFolders = [],
scannedFiles = [];
if(Array.isArray(data)) {
data.forEach(function (d) {
if (d.type === 'folder') {
scannedFolders.push(d);
}
else if (d.type === 'file') {
scannedFiles.push(d);
}
});
}
else if(typeof data === 'object') {
scannedFolders = data.folders;
scannedFiles = data.files;
}
// Empty the old result and make the new one
fileList.empty().hide();
if(!scannedFolders.length && !scannedFiles.length) {
filemanager.find('.nothingfound').show();
}
else {
filemanager.find('.nothingfound').hide();
}
if(scannedFolders.length) {
scannedFolders.forEach(function(f) {
var itemsLength = f.items.length,
name = escapeHTML(f.name),
icon = '<span class="icon folder"></span>';
if(itemsLength) {
icon = '<span class="icon folder full"></span>';
}
if(itemsLength == 1) {
itemsLength += ' item';
}
else if(itemsLength > 1) {
itemsLength += ' items';
}
else {
itemsLength = 'Empty';
}
var folder = $('<li class="folders">'+icon+'<span class="name">' + name + '</span> <span class="details">' + itemsLength + '</span></li>');
folder.appendTo(fileList);
});
}
if(scannedFiles.length) {
scannedFiles.forEach(function(f) {
var fileSize = bytesToSize(f.size),
name = escapeHTML(f.name),
fileType = name.split('.'),
icon = '<span class="icon file"></span>';
fileType = fileType[fileType.length-1];
icon = '<span class="icon file f-'+fileType+'">.'+fileType+'</span>';
var file = $('<li class="files">'+icon+'<span class="name">'+ name +'</span> <span class="details">'+fileSize+'</span></li>');
file.appendTo(fileList);
});
}
// Generate the breadcrumbs
var url = '';
if(filemanager.hasClass('searching')){
url = '<span>Search results: </span>';
fileList.removeClass('animated');
}
else {
fileList.addClass('animated');
breadcrumbsUrls.forEach(function (u, i) {
var name = u.split('/');
if (i !== breadcrumbsUrls.length - 1) {
url += '<span class="folderName">' + name[name.length-1] + '</span> <span class="arrow">→</span> ';
}
else {
url += '<span class="folderName">' + name[name.length-1] + '</span>';
}
});
}
breadcrumbs.text('').append(url);
// Show the generated elements
fileList.animate({'display':'inline-block'});
}
// This function escapes special html characters in names
function escapeHTML(text) {
return text.replace(/\&/g,'&').replace(/\</g,'<').replace(/\>/g,'>');
}
// Convert file sizes from bytes to human readable units
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Bytes';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
});
});
I tweaked certain jquery methods around in the render function using the 1.11.3 version and it appears animate() was causing the issues.
Change Script.js line 375:
From fileList.animate({'display':'inline-block'});
To fileList.css('display','inline-block');.
EDIT:
I noticed a slightly more improved method of revealing the hidden filelist without using inline styles and adding it to a more appoporate section of the script. Simply use filelist.show() in the following section of the render function.
change Script.js line 286-291:
if(!scannedFolders.length && !scannedFiles.length) {
filemanager.find('.nothingfound').show();
fileList.hide();
}
else {
filemanager.find('.nothingfound').hide();
fileList.show();
}
Hiding the filelist using filelist.hide() also helped me with a style bug relating to the .nothing-found error message being pushed down to the bottom of the page when needing to use a fixed height on the filelist.
Now im not depenedant on what version of jquery im using. Hope this helps others using this nice little script.
function displayPreview(files) {
var reader = new FileReader();
var img = new Image();
reader.onload = function (e) {
img.src = e.target.result;
fileSize = Math.round(files.size / 1024);
if(fileSize>50) {
ret1=false;
alert("File size is " + fileSize + " kb");
return ret1;
} else {
var ret1 = true;
return ret1;
}
img.onload = function () {
if(this.width!="181" && this.height!="181") {
ret1=false;
alert("width=" + this.width + " height=" + this.height);
return ret1;
} else {
var ret1 = true;
return ret1;
}
console.log("width=" + this.width + " height=" + this.height+"File size is " + fileSize + " kb");
};
};
reader.readAsDataURL(files);
}
function chkform() {
var ret = false;
if (document.getElementById("file").value === "") {
console.log("empty");
} else {
var file = document.getElementById("file").files[0];
var tt=displayPreview(file);
console.log(tt+"nis");
}
return ret;
}
When a user clicks on the submit button, the form has an onsubmit="return chkform();", then my checkform checks if the id name file is empty or not.
If not, then it call the function displayPreview(). In that function I am checking whether the size is not more than 50 and width and height is not equal to width="181px" and height="181px".
I am returning ret through which I can get the information it's returning true or false
but In my checkform I am getting UNDEFINED... why?
Edit
Added reproduction code at JSFIddle: http://jsfiddle.net/nishit_bhardwaj/zaukV/
Sorry I didn't work with your code but this is how you can get the filesize. After that it's easy to validate. You also could disable or hide the submit/upload-button if the filesize is incorrect:
http://jsfiddle.net/rq8nA/
JS:
$("input:file").change(function () {
if ($(this).val() !== "") {
var file = $('#file_select')[0].files[0];
console.log(file.size);
}
});
HTML:
<input type="file" name="file" id="file_select" />
I added something to get width and preview image too:
http://jsfiddle.net/rq8nA/1/