On clicking the submit button it is not giving appropriate result - javascript

Hello ,
I am having some problem with javascript & Html..In my code i am reading excel file from directory and showing some output..for this i have a file input type and a Button...what is happening here is when i select the xls file and click on submit button Choose a file widow is opening every time when i am clicking on the submit button ..
the code is as follows
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Speedometer HTML5 Canvas</title>
<script src="script copy.js"></script>
</head>
<body onload='draw(0);'>
<canvas id="tutorial" width="440" height="220">
Canvas not available.
</canvas>
<div>
<form id="drawTemp">
<input type="text" id="txtSpeed" name="txtSpeed" value="20" maxlength="2" />
<input type="button" value="Draw" onclick="drawWithInputValue();">
<input type=file id="fileInput" value="">
<input type=button value="submit" onclick="readdata(1,1);">
</form>
</div>
</body>
</html>
<script type="text/javascript" language="javascript">
function checkfile(sender) {
var validExts = new Array(".xlsx", ".xls", ".csv");
var fileExt = sender.value;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0) {
alert("Invalid file selected, valid files are of " +
validExts.toString() + " types.");
return false;
}
else return true;
}
var xVal = 1;
var yVal = 2
function readdata(x,y) {
x = xVal;
y = yVal;
// Use the <input type='file'...> object to get a filename without showing the object.
document.all["fileInput"].click();
var fileName = document.all["fileInput"].value;
try {
var excel = new ActiveXObject("Excel.Application");
excel.Visible = false;
var excel_file = excel.Workbooks.Open(fileName);
var excel_sheet = excel_file.Worksheets("Sheet1");
var data = excel_sheet.Cells(x, y).Value;
//alert(data);
drawWithexcelValue(data);
xVal = xVal + 1;
}
catch (ex) {
alert(ex);
}
}
</script>
Every time i click on the submit button it opens the choose window to choose file ..why my button is behaving like file type input..

It's opening the "choose file" dialog because of this line in your Javascript:
document.all["fileInput"].click();
If you remove that, you won't get this behaviour.

document.all["fileInput"].click();
when you click on submit this line in the readdata() function is programmatically clicking on the choose file button.

Related

Can only assign "" as value to input type file

I've the following code that checks if I file is .jpg,.jpeg or .png:
<!DOCTYPE html>
<html>
<body>
<input type="file" align="center" accept=".jpg,.jpeg,.png" onchange="this.size = Math.max(this.value.length, 7)+15;read(this)" id="myinput" style="min-width: 50px;"
/>
</body>
</html>
<script>
var myfile=""
async function read(input) {
var file = input.files[0];
var idxDot = file.name.lastIndexOf(".") + 1;
var extFile = file.name.substr(idxDot, file.name.length).toLowerCase();
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
//fileContent = await readFile(file);
myfile=file
alert("Valid file selected!");
}else{
alert("Only jpg, jpeg or png allowed");
input.value = myfile;
}
}
</script>
I'm attempting that if a file different to that ones is selected the last value of a taken valid file displays.
But that only happens, at the beginning, after a valid file has been taken. if I choose another one the path shown in the input changes to that of the selected file even if it's not a valid one.
Is there any way to solve this issue so the path that displays is always the one of the last valid file?
a little bit of a hack but may give you what you need
var myfile={name:"none"};
function read(input) {
var file = input.files[0];
var idxDot = file.name.lastIndexOf(".") + 1;
var extFile = file.name.substr(idxDot, file.name.length).toLowerCase();
var span =document.getElementById('last');
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
//fileContent = await readFile(file);
myfile=file
alert("Valid file selected!");
span.style.display='none';
}else{
alert("Only jpg, jpeg or png allowed");
input.value = '';
span.style.display='inline';
span.innerHTML = "Last valid File was: " + myfile.name
}
}
span{
display:none;
}
<!DOCTYPE html>
<html>
<body>
<input type="file" align="center" accept=".jpg,.jpeg,.png" onchange="this.size = Math.max(this.value.length, 7)+15;read(this)" id="myinput" style="min-width: 50px;"
/>
<span id='last'></span>
</body>
</html>

Get the extension of a file but can't get the filename

I am trying to check if a file has a valid extension or not. The problem is that when I give the file a random extension like .txt it doesn't get caught.
I think the problem is that I am not actually getting the full filename.
<script type="text/javascript">
function getExtension(fileName)
{
var parts = fileName.split('.');
return parts[parts.length - 1];
}
function isVideo(fileName)
{
var ext = getExtension(fileName);
switch (ext.toLowerCase())
{
case 'mp4': return true;
}
return false;
}
function check()
{
var f = document.getElementsByID('file');
if(isVideo(f.value) && document.getElementById('file').value)
{
return true;
}
document.getElementById('errMsg').style.display = '';
return false;
}
</script>
The PHP form:
<?php
$nexturl = "http://localhost/index.php";
?>
<form action="<?php echo($response->url); ?>?nexturl=<?php echo(urlencode($nexturl)); ?>" method="post" enctype="multipart/form-data" onsubmit="return check();">
<input id="file" type="file" name="file"/>
<div id="errMsg" style="display:none;color:red">
Bad file type.
</div>
<input type="hidden" name="token" value="<?php echo($response->token); ?>"/>
<input type="submit" value="go" />
</form>
</php>
You could first obtain the file extension and then do what you need to with it:
var patt1 = /\.[0-9a-z]+$/i;
var fileName = "file.zip";
var theReturn = fileName.match(patt1);
alert(theReturn); //returns .zip
So, in your code, you would need to switch your switch statement to the following:
function isVideo(fileName)
{
var patt1 = /\.[0-9a-z]+$/i;
var fileName = "file.zip";
var theReturn = fileName.match(patt1);
switch (theReturn.toLowerCase())
{
case '.mp4': return true; //make sure it's .mp4 instead of just mp4
}
retrun false
}
EDIT
Example to get file name and extension of uploaded file to FileUpload control:
HTML
<!DOCTYPE Html />
<html>
<head>
<title></title>
</head>
<body>
<input id="File1" type="file" />
<input type="button" id="btnGetExt" value="Get File Extension"/>
<script type="text/javascript" src="theJS.js"></script>
</body>
</html>
JavaScript
btnGetExt.onclick = function () {
var patt1 = /\.[0-9a-z]+$/i;
var fileName = document.getElementById('File1').value;
alert(fileName);
var theReturn = fileName.match(patt1);
alert(theReturn);
}

Get a value from Javascript

I want to get the value that I entered in the prompt, and save it in a variable to use it to update a DB later .. I try this but is does not work !!
#{
var fileName = "";
var db = Database.Open( "GP" );
var sqlupdate = "Update rc_Files set fileName=#0 Where fileID= 5";
db.Execute(sqlupdate, fileName);
}
<html lang="en">
<body>
<script>
function myFunction() {
newName = prompt("Please enter new file name :");
if (newName != null)
{
#fileName = newName;
}
}
</script>
</body>
</html>
JavaScript is client side language. You can't updated db with it. You can send request to your server side script, which will update something in datatable.
You can find example of doing this here or just use google.
Try this code:
$(document).ready(function() {
var fileName = '';
var newName = prompt('Please enter a new file name');
if(newName != null) {
fileName = newName;
console.log(fileName);
}
});
Its getting the value you entered through javascript.
Demo here
From your question is not clear what is your goal.
If you want to store a value in your page waiting to use it when the page is posted, you could use a hidden input field.
In my example the value inputed when the page is loaded is stored until the user clicks the submit button:
#{
if(IsPost){
var fileName = Request["fileName"];
var db = Database.Open("GP");
var sqlupdate = "Update rc_Files set fileName=#0 Where fileID= 5";
db.Execute(sqlupdate, fileName);
}
}
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<form method="post">
<input type="hidden" name="fileName" id="fileName" value="" />
<input type="submit" />
</form>
<script>
$(document).ready(function () {
var newName = prompt('Please enter a new file name');
$('#fileName').val(newName);
});
</script>
</body>
</html>
Else, if you want to update your database without submitting your page, you should use Ajax. This article could help you: Posting Data With jQuery AJAX In ASP.NET Razor Web Pages.

Javascript disabling input fields

I am looking for a javascript function. which will disable the entered (filled) text field on submit. So when the user logs in back the filled text box has to remain disabled. I have tried a code, but here what happens is on clicking the sumbit the contents in the text field gets deleted.
<html>
<head>
<script>
function enableDisable(){
var disable = true;
var arglen = arguments.length;
var startIndex = 0;
var frm = document.example1;//change appropriate form name
if (arglen>0){
if (typeof arguments[0]=="boolean") {
disable=arguments[0];
if (arglen>1) startIndex=1;
}
for (var i=startIndex;i<arglen;i++){
obj = eval("frm."+arguments[i]);
if (typeof obj=="object"){
if (document.layers) {
if (disable){
obj.onfocus=new Function("this.blur()");
if (obj.type=="text") obj.onchange=new Function("this.value=this.defaultValue");
}
else {
obj.onfocus=new Function("return");
if (obj.type=="text") obj.onchange=new Function("return");
}
}
else obj.disabled=disable;
}
}
}
}
</script>
</head>
<body>
<form name="example1">
Text Field: <input type="text" name="text1">
<br>
<input type="submit" name="control1" onclick="enableDisable(this.submit,'text1','submit','select1')">
</form>
</body>
</html>
please do guide.
Make sure your submit function returns false if you don't want the page to refresh. The code you're looking for is document.getElementById('insertIdOfTextFieldHere').style.readonly = "readonly";

how to get file size in javascript or jquery with rails

how to get file size in javascript or jquery with rails here by word size i means to say content size of file like 100kb.
here i got some methods like size or file size but its not working for me
my ruby code is
<%= upload_form.file_field :upload_file_name1,:onchange =>"return validateFileExtension(this)"%>
function validateFileExtension(fld) {
alert(fld.value.fileSize);
if(!/(\.jpg|\.gif|\.png)$/i.test(fld.value)) {
alert("Invalid file type! Kindly upload in a JPG, GIF or PNG format!");
fld.parentNode.innerHTML = fld.parentNode.innerHTML;
fld.focus();
return false;
}
return true;
}
<html>
<head>
<script language="JavaScript">
function A()
{
var oas = new ActiveXObject("Scripting.FileSystemObject");
var d = document.a.b.value;
var e = oas.getFile(d);
var f = e.size;
alert(f + " bytes");
}
</script>
</head>
<body>
<form name="a">
<input type="file" name="b">
<input type="button" name="c" value="SIZE" onClick="A();">
</form>
</body>
</html>

Categories

Resources