Below is my javascript code and what I want to happens is that when the user clicks on the “Upload” button in the form, it does a check in the “imageValidation” to see if the file input is correct, if so then it goes onto the “startImageUpload()” function, if file input is incorrect then it should display an alert stating “not an image” and it shouldn’t go to the ‘startImageUpload’ function.
Problem is that it is not doing this at all. When the user clicks on the “Upload” button then no alert appears, no upload happens, nothing happens. What do I need so that I can achieve the above paragraph?
Below is the form:
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='imageClickHandler(this); return false;' class='imageuploadform' >" +
"<label> Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label></form>");
Below is the function where when the user clicks on the “Upload” button, it follows this function below:
function imageClickHandler(){
if(imageValidation()){
startImageUpload(imageuploadform);
}
}
Below is the imageValidation() function where it validates the file input but I do not know if this is working correctly?
function imageValidation() {
$(".fileImage").change(function() {
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
case 'gif': case 'jpg': case 'png':
return true;
break;
default:
$(this).val('');
// error message here
alert("not an image");
return false;
break;
}
});
}
Below is the ‘startImageUpload()’ function which I know it works before attempting to validate the input file.
function startImageUpload(imageuploadform){
$(imageuploadform).find('.imagef1_upload_process').css('visibility','visible');
$(imageuploadform).find('.imagef1_cancel').css('visibility','visible');
$(imageuploadform).find('.imagef1_upload_form').css('visibility','hidden');
sourceImageForm = imageuploadform;
return true;
}
your
onsubmitalways returnsfalse…change it to return the result of
imageClickHandlerand change the JS function to return value
also – make sure that your
imageValidationfunction has a default return value (addreturn false;at the last row of the function)EDIT:
in order to prevent the validation from being happened when the user chooses file, remove the listening to the change event, and change your validation to: