In the following code I am trying to check if the file is selected or not from the hyperlink. When the file is selected for the first time the var fileName = $('#' + field_id).val(); is null but when the file is selected for the second time the file path is shown. What is wrong here?
<input type="file" id="new_rule_upload" name="new_rule_upload" style="visibility: hidden; width: 1px; height: 1px" />
Upload
function upload_file(field_id) {
var fileName = $('#' + field_id).val();
alert(fileName);
if (fileName != '') {
alert('selected')
} else {
alert('not selected');
}
}
I suggest attaching yourself to the change event of the input to you can be immediately notified.
$(function() {
$("#new_rule_upload").change(function (){
var fileName = $(this).val();
// Do something
});
});
use JQuery
$(function() {
$("#a_id").click(function() {
var fileName = $("#new_rule_upload").val();
alert(fileName);
if (fileName != '') {
alert('selected')
} else {
alert('not selected');
}
});
});
Related
I am trying to automatically prompt a user to upload a CSV file and then I plan to access the data within, but I am unable to do this. What am I doing wrong? input.name is always undefined and viewing the whole object doesn't provide any relevant details.
The source of this query primarily came from the answer to this question Open file dialog box in JavaScript. I am trying to achieve this purely in javascript, not HTML.
jsfiddle
$(document).ready(function() {
var input = $(document.createElement('input'));
input.attr("type", "file");
input.on('change',function(){
alert(JSON.stringify(input.name, null, 4));
alert(JSON.stringify(input, null, 4));
});
input.trigger('click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
input is the return value of $(). It is a jQuery object not a DOM object. To access the name property of the underlying DOM object, use the prop method.
input.prop('name')
I finally got it working. Here is the solution
$(document).ready(function() {
var input = $(document.createElement('input'));
input.attr("type", "file");
input.on('change', function() {
var csvFile = input[0].files[0];
var ext = csvFile.name.split(".").pop().toLowerCase();
if (ext != "csv") {
alert('upload csv');
return false;
}
if (csvFile != undefined) {
reader = new FileReader();
reader.onload = function(e) {
var data = $.csv.toObjects(e.target.result);
alert(JSON.stringify(data, null, 4));
$.each(data, function(index, val) {
//do something with each row of data val.ColumnName
});
}
reader.readAsText(csvFile);
}
});
input.trigger('click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/1.0.21/jquery.csv.js"></script>
Updated method with security implementations in place: 2023-01-24
You just can't use the document ready function but have to force the user to initiate the file open dialog:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
console.log(jQuery(). jquery);
$("#file-upload").click(function() {
var input = $(document.createElement('input'));
input.attr("type", "file");
input.on('change', function() {
var csvFile = input[0].files[0];
var ext = csvFile.name.split(".").pop().toLowerCase();
if (ext != "csv") {
alert('upload csv');
return false;
}
if (csvFile != undefined) {
reader = new FileReader();
reader.onload = function(e) {
var data = $.csv.toObjects(e.target.result);
alert(JSON.stringify(data, null, 4));
$.each(data, function(index, val) {
//do something with each row of data val.ColumnName
});
}
reader.readAsText(csvFile);
}
});
input.trigger('click');
});
</script>
</head>
<body>
Upload file
</body>
</html>
I am working on some legacy code which is using Asp.net and ajax where we do one functionality to upload a pdf. To upload file our legacy code uses AjaxUpload, but I observed some weird behavior of AjaxUpload where onComplete event is getting called before actual file got uploaded by server side code because of this though the file got uploaded successfully still user gets an error message on screen saying upload failed.
And here the most weird thins is that same code was working fine till last week.
Code:
initFileUpload: function () {
debugger;
new AjaxUpload('aj-assetfile', {
action: '/Util/FileUploadHandler.ashx?type=asset&signup=False&oldfile=' + assetObj.AssetPath + '&as=' + assetObj.AssetID,
//action: ML.Assets.handlerPath + '?action=uploadfile',
name: 'AccountSignupUploadContent',
onSubmit: function (file, ext) {
ML.Assets.isUploading = true;
ML.Assets.toggleAsfMask(true);
// change button text, when user selects file
$asffile.val('Uploading');
$astfileerror.hide();
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
ML.Assets.interval = window.setInterval(function () {
var text = $asffile.val();
if (text.length < 13) {
$asffile.val(text + '.');
} else {
$asffile.val('Uploading');
}
}, 200);
//if url field block is visible
if ($asseturlbkl.is(':visible')) {
$asfurl.val(''); //reset values of url
$asfurl.removeClass('requiref error'); //remove require field class
$asfurlerror.hide(); //hide errors
}
},
onComplete: function (file, responseJSON) {
debugger;
ML.Assets.toggleAsfMask(false);
ML.Assets.isUploading = false;
window.clearInterval(ML.Assets.interval);
this.enable();
var success = false;
var responseMsg = '';
try {
var response = JSON.parse(responseJSON);
if (response.status == 'success') { //(response.getElementsByTagName('status')[0].textContent == 'success') {
success = true;
} else {
success = false;
responseMsg = ': ' + response.message;
}
} catch (e) {
success = false;
}
if (success) {
assetObj.AssetMimeType = response.mimetype;
$asffile.val(response.path);
$asffile.valid(); //clear errors
ML.Assets.madeChanges();
if (ML.Assets.saveAfterUpload) { //if user submitted form while uploading
ML.Assets.saveAsset(); //run the save callback
}
} else { //error
assetObj.AssetMimeType = "";
$asffile.val('');
$astfileerror.show().text('Upload failed' + responseMsg);
//if url field block is visible and type is not free offer.
if ($asseturlbkl.is(':visible') && this.type !== undefined && assetObj.AssetType != this.type.FREEOFFER) {
$asfurl.addClass('requiref'); //remove require field class
}
ML.Assets.hideLoader();
}
}
});
}
I was facing the same issue but I fixed it with some minor change in plugin.
When “iframeSrc” is set to “javascript:false” on https or http pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue.
Old Code:
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
New Code with chagnes:
var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');
After changing the code it's working fine. I hope it will work for you as well. :)
Reference (For more details): https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/
I wanted to redirect the user on another url when I type a certain word in a textera.
I tried something but it doesn't work. I don't have a lot of knowledge in javascript and jquery so could someone check my code?
var url = "https://myURL";
$('.button').on('click', function() {
if ($("textarea").is(':contains("test")'))
$(location).attr('href',url);
else
alert("Wrong word !");
});
in this can search or indexOf method can be used as follows:
var url = "https://myURL";
$('.button').on('click', function() {
var introString = $("#introduction").val();
if(introString.indexOf("test") >= 0){
$("#location").attr('href',url);
}else{
alert("Wrong word !");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="introduction"></textarea>
<button class="button">Submit</button>
Browse
var url = "https://myURL";
$('.button').on('click', function() {
var textval = $("textarea").val();
if (textval.indexOf('test') !=-1) {
window.open(url)
} else {
alert("Wrong word !");
}
});
I'm doing upload multiple files(use <input type="file" multiple/>) with preview image file and can remove the image preview and filedata successfully.
but the problem is, I cannot change the selector for onclick to remove filedata.
(If I change to other selector, it will only remove the preview image but the files still be uploaded to my folder)
The selector for click to remove that work successfully is .selFile but when
I want to change selector for onclick to .selFile2 it will not remove filedata)
these are my focus line of code. (To see my Full code, Please look on bottom)
var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile'
title='Click to remove'> <span class='selFile2'>" + f.name + "</span><br clear=\"left\"/></div>";
..
I change from
$("body").on("click", ".selFile", removeFile);
to
$("body").on("click", ".selFile2", removeFile);
but it remove preview image only not remove filedata (it's still be uploaded to my folder)
..
And I try to change code in function removeFile(e)
from var file = $(this).data("file"); to var file = $('.selFile).data("file"); the result is It can remove only 1 filedata.
...
How could I do?
Here is my full code (2 pages)
firstpage.html (I use ajax to post form)
<!doctype html>
<html>
<head>
<title>Proper Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
#selectedFiles img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom:10px;
cursor:pointer;
}
</style>
</head>
<body>
<form id="myForm" method="post">
Multiple Files: <input type="file" id="files" name="files[]" multiple><br/>
<div id="selectedFiles"></div>
<input type="submit">
</form>
<script>
var selDiv = "";
var storedFiles = [];
$(document).ready(function() {
$("#files").on("change", handleFileSelect);
selDiv = $("#selectedFiles");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".selFile", removeFile);
});
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
filesArr.forEach(function(f) {
if(!f.type.match("image.*")) {
return;
}
storedFiles.push(f);
var reader = new FileReader();
reader.onload = function (e) {
var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile' title='Click to remove'> <span class='selFile2'>" + f.name + "</span><br clear=\"left\"/></div>";
selDiv.append(html);
}
reader.readAsDataURL(f);
});
}
function handleForm(e) {
e.preventDefault();
var data = new FormData();
for(var i=0, len=storedFiles.length; i<len; i++) {
data.append('files[]', storedFiles[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText + ' items uploaded.');
}
}
xhr.send(data);
}
function removeFile(e) {
var file = $(this).data("file");
for(var i=0;i<storedFiles.length;i++) {
if(storedFiles[i].name === file) {
storedFiles.splice(i,1);
break;
}
}
$(this).parent().remove();
}
</script>
</body>
</html>
..
upload.php page
<?php
for($i=0;$i < count($_FILES["files"]["name"]);$i++)
{
if($_FILES["files"]["name"][$i] != "")
{
$tempFile = $_FILES['files']['tmp_name'][$i];
$targetFile = "upload/". $_FILES["files"]["name"][$i];
move_uploaded_file($tempFile,$targetFile);
}
}
?>
It is because when the browser listens to the click event for a .selFile2 element, the img tag becomes the sibling of the event.target (the .selFile2).
Once you delegate the click events to the span tags, $("body").on("click", ".selFile2", removeFile);
You just need to modify your removeFile function a little bit like below.
function removeFile(e) {
var img = e.target.parentElement.querySelector("img");
var file = img.getAttribute('data-file');
for(var i=0;i<storedFiles.length;i++) {
if(storedFiles[i].name === file) {
storedFiles.splice(i,1);
break;
}
}
$(this).parent().remove();
}
I have just tested the code and and it is working on my end.
I can upload a file from the form below, selecting a file from the file chooser. But the problem is when I try to submit the form with the same file again, it doesn't do anything.
I choose a file from the file chooser, upload it. I choose the same file again, then I can't upload it again. But if I upload the file after I try a different file, then I can upload the same file again.
What is wrong with the codes below.
I have included jquery for the script and html for the form. I don't really understand what's going wrong with them.
$(document).ready(function() {
$("#datauploadbtn").on('click', function() {
$('#datafile').trigger('click');
});
$('#datafile').change(function(e) {
//var reg=/(.txt)$/;
//if (!reg.test($("#myFile").val())) {
// alert('Only .txt file extension allowed!');
// return false;
//} else {
$("#datafiletxt").val($("#datafile").val());
if ($("#datafiletxt").val() == '') {
alert('Select a file to upload');
return false;
} else {
$('#dataform').submit();
e.preventDefault();
}
});
});
$(function() {
var bar = $('.barTest');
var percent = $('.percentTest');
var status = $('#statusTest');
$('#dataform').ajaxForm({
success: function(data) {
console.log(data);
$('#percentTest').css('visibility', 'hidden');
$('#percentTest').css('color', ' white');
$('#barTest').css('background-color', 'white');
$('#statusTest').css('color', 'white');
$('#progressTest').css('border', '1px solid white');
$('#percentSpan').css('visibility', 'hidden');
$('#statusSpan').css('visibility', 'hidden');
//status.empty();
alert('Successfully uploaded!');
},
beforeSend: function() {
$('#percentTest').css('visibility', 'visible');
$('#percentTest').css('color', ' black');
$('#barTest').css('background-color', '#B4F5B4');
$('#statusTest').css('color', 'orange');
$('#progressTest').css('border', '1px solid #ddd');
$('#percentSpan').css('visibility', 'visible');
$('#statusSpan').css('visibility', 'visible');
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
console.log(percentVal);
}
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<form action="ajaxasync" enctype="multipart/form-data" method="post" name="dataform" id="dataform">
<input type="button" value="Data file" id="datauploadbtn" name="datauploadbtn" style="width:100px; font:12px 'Arial'; font-weight:bold; height:30px; background:lightblue;" />
<input type="text" id="datafiletxt" style="width:260px; font:12px 'Arial'; font-weight:bold; height:27px;" />
<input type="file" name="datafile" id="datafile" style="visibility:hidden;" />
</form>
<div id="progressTest" class="progressTest">
<div id="barTest" class="barTest"></div >
<div id="percentTest" class="percentTest" style="visibility:hidden;"></div>
</div>
<div id="statusTest" style="font:11px 'Arial'; color: orange;">
<span id="statusSpan" style="visibility:hidden;">
File uploading in progress... <br>
Please wait!
</span>
</div>
You currently using ON CHANGE event. If you select same file the value will still remain constant. So that mean you need to change the value to empty once you grab the value form the on change event
$(document).ready(function() {
$("#datauploadbtn").on('click', function() {
$('#datafile').trigger('click');
});
$('#datafile').change(function(e) {
//var reg=/(.txt)$/;
//if (!reg.test($("#myFile").val())) {
// alert('Only .txt file extension allowed!');
// return false;
//} else {
$("#datafiletxt").val($("#datafile").val());
if ($("#datafiletxt").val() == '') {
alert('Select a file to upload');
return false;
} else {
$('#dataform').submit();
e.preventDefault();
}
$("#datafile").val("");//this is the changd!!!
});
});
I comment the code you need to insert
When you are uploading a file via ajax the input values and the file are still on the form you must clear the form $('#dataform')[0].reset(); or clear the value of the input $("#datafiletxt").val(""); which triggers the upload button.