reading Excel file on Javascript - javascript

I want to read only one row each time on excel. I can read all datas in excel but I couldn't limit it. Either I can read only 1 column in all rows or the all data. How can I read just 1 row on javascript?
I use this script and this src:
<script src="https://unpkg.com/read-excel-file#4.x/bundle/read-excel-file.min.js"></script>
<body>
<input type="file" id="input">
<script>
var input = document.getElementById('input');
input.addEventListener("change", function (){
readXlsxFile(input.files[0]).then(function (data){
data.map((row,index)=>{
var location= document.createTextNode(row);
console.log(location)

If you need one row, don't map over entire file:
readXlsxFile(input.files[0]).then(data => {
console.log(data[0]) // supposed to print the first row
})

Related

How to make sure File is read completely by FileReader using Javascript

I have various HTML elements defined in an XML file.
I cant be able to display my XML element as whole but it has multiple rows and each row consists of checkboxes, File upload option, etc.
I am using Javascript to get these elements and then using XMLHTTPRequest, sending these requests to the controller to process.
Imagine HTML elements be like below:
Row1 ---- Checkbox1_Row1 TextDescription_Row1 FileUpload_Row1
Row2 ---- Checkbox1_Row2 TextDescription_Row2 FileUpload_Row2
I can have how many ever rows as possible.
Using Javascript, I am getting all these form elements and these elements are differentiated by Row number (Row1, Row2).
I am looping through each form elements and then
for(var j=0; j< formelements.length; j+++)
{
if (formElements[j].type == "textbox")
{
Do something
}
elseif (formElements[j].type == "file")
{
var Base64String;
var ready = false;
var fileName = formElements[j].files[0].name;
var check = function () {
if (ready === true) {
array.push(Base64String);
return;
}
setTimeout(check, 1000);
}
check();
var reader = new FileReader();
reader.onloadend = function (evt) {
Base64String = evt.target.result;
ready = true;
};
reader.readAsDataURL(file);
}
}
I am using an array to push all the values corresponding to each row and the array with final value will be sent to the controller after some alterations. Here for file upload option, I am reading the file from each row and converting them into binary format and sending to the controller. This approach works fine, if there is only one row. What happens with this approach when there are multiple rows is, while looping through the form element, it check everything for the first row (say textbox) and puts into the array but when it is file type, it goes to the loop and reads the file. Reading the file takes sometime here and by the time loop goes to the next form element (which is nothing but Row2). Now Row2 form element comes into picture and say, we do not upload any file, it will be null. Now check() function gets completed and file from row1 is read completely. Since the loop is already in for Row 2 form element, this file value is getting assigned to Row2 apart from null values. So Row2 will have both null value and file value when it comes to file type but there is no value for Row1. Similarly if I have many files in multiple rows, the file value gets assigned to which ever row form element that is there in current loop based on the time read by FileReader.
I need to make sure that file value is read completely before moving on to the next form element. How to achieve this?
************************Updates**********************
The question which was referred here marking mine as duplicate has only file type coming in and hence, they can loop through the file type. For me, form elements consists of Checkbox1_Row1, TextDescription_Row1, FileUpload_Row1, Checkbox1_Row2 , TextDescription_Row2, FileUpload_Row2.
I have to make sure that FileUpload_Row1 has right value read from the file before moving on to to next form element, here Checkbox1_Row2.
evt should be event at evt.target.result. .push() event.target.result to fileList array, do stuff when fileList .length is equal to count
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var files = Array.prototype.map.call(
document.querySelectorAll("[id^=myFile]")
, function(input) {
return {id:input.dataset.id, file: input.files[0]};
});
var count = files.length; // total number of files
var fileList = []; // accepted files
for (var i = 0; i < count; i++) {
var file = files[i].file;
var id = files[i].id;
var filename = files[i].file.name;
if (i >= count) {
break;
}
var reader = new FileReader();
reader.onload = (function(id, filename) {
return function(event) {
fileList.push({id, filename, file:event.target.result}); {
if (fileList.length === count) {
// do stuff with `fileList`
console.log(fileList);
}
}
}
})(id, filename);
reader.readAsDataURL(file);
}
}
</script>
</head>
<body>
<h1>Hello Plunker!</h1>
<input type="file" id="myFile_row1" data-id="A">
<input type="file" id="myFile_row2" data-id="B">
<input type="file" id="myFile_row3" data-id="C">
<button onclick="myFunction()">Try it</button>
</body>
</html>
plnkr http://plnkr.co/edit/VCGPPbWcock0PgC9wMWi?p=preview

Append incremented number to multiple uploaded images using JavaScript

Append incremented number to multiple uploaded images using JavaScript
I'm trying to upload multiple images to our HP Records Manager Database using the ServiceAPI .NET SDK. Written in ASP.NET MVC.
The images upload successfully but they all have the same Title as it uses the same input field.
I want to be able to create a loop that will append an incremented number to the end of the Record Title. (e.g Upload_1, Upload_2, Upload_3....and so on)
<form action="Record" method="post" enctype="multipart/form-data">
<input id="gpsearchtitle" type="text" name="RecordTypedTitle" value="" required="True"/>
<input id="choose" type="file" name="upload" multiple="multiple"/>
<button type="submit">Upload</button>
</form>
Is there a way of appending a incremented number using JavaScript?
Update
I have tried doing this:
<script>
function appendNo(){
var inp = document.getElementById('choose');
var txt = document.getElementById('gpsearchtitle')
for (var i = 0; i < inp.files.length;) {
var name = inp.files.item(i).name;
txt.value = txt.value + "_" + i;
i++;
}}
</script>
However, this adds the incremental count to all image Titles. For example if i upload 4 images the Titles show up as, Upload_0_1_2_3, Upload_0_1_2_3, Upload_0_1_2_3, Upload_0_1_2_3
Try grabbing each title (after loading dom elements) and setting them incrementally:
<script type="text/javascript">
function pageLoad() {
var titles = $('input[name="RecordTypedTitle"]');
for (t in titles)
{
titles[t].val(t);
}
}
</script>
Then in body, include the parameter onload="pageLoad();"

Excel data into html output

I have managed to find out how to pull data from a excel file into HTML.
I am now trying to look how to search for values within a set of cells. Does anyone know how to achieve this?
Thanks in advance!
jQuery is likely going to help you with that. when building the HTML i would also add data-[somethingHelpfulWhenSearching] or add class values that could help.
then you can search for the item by class
$('.[searchableClassName]')
or by data attribute:
$('[data-[somethingHelpfulWhenSearching]') //only looking that the tag exists
$('[data-[somethingHelpfulWhenSearching]="something im looking for"') //only looking that the tag and checking the value
hope this helps
From the way you worded the question, it sounds like you have a table in your HTML, and you just want to loop over all of the cells to check which cells contain a given value, and return those DOM nodes that contain the provided search string within their text content. If that's an accurate interpretation, here is a Vanilla JS solution:
function findCells(str) {
var allCells = document.querySelectorAll("td");
var matchingCells = [];
for (var i = 0; i < allCells.length; i++) {
if (allCells[i].textContent.indexOf(str) !== -1) {
matchingCells.push(allCells[i]);
}
}
return matchingCells;
}
<html>
<script>
function mytest1() {
var Excel, Book; // Declare the variables
Excel = new ActiveXObject("Excel.Application"); // Create the Excel application object.
Excel.Visible = false; // Make Excel invisible.
Book = Excel.Workbooks.Add() // Create a new work book.
Book.ActiveSheet.Cells(2, 2).Value = document.all.my_textarea1.value;
Book.SaveAs("C:/temp/TEST.xls");
Excel.Quit(); // Close Excel with the Quit method on the Application object.
}
function mytest2() {
var Excel;
Excel = new ActiveXObject("Excel.Application");
Excel.Visible = false;
form1.my_textarea2.value = Excel.Workbooks.Open("C:/temp/TEST.xls").ActiveSheet.Cells(1, 1).Value;
Excel.Quit();
}
</script>
<body>
<form name="form1">
<input type=button onClick="mytest1();" value="Send Excel Data">
<input type=text name="my_textarea1" size=70 value="enter ur data here">
<br><br>
<input type=button onClick="mytest2();" value="Get Excel Data">
<input type=text name="my_textarea2" size=70 value="no data collected yet">
</form>
</body>
</html>
Since you're already using jQuery, try DataTables, which is a jQuery plugin and does a lot more than filtering for you. It allows for both client side and server side filtering, so it's not a problem if your table is large.

Grails richui autocomplete passing object to function or updating object ID

I've got a table with a load of auto complete boxes in it which look like so...
<richui:autoComplete style="width:500px" name="objSelect[${newRow-1}].id" value= "" action="${createLinkTo('dir': 'object/searchAJAX')}" forceSelection = "true" maxResultsDisplayed="20" minQueryLength ="3" onItemSelect="updateHiddenInput(id,${newRow-1})" />
I've got it to call a function called updateHiddenInput when a user selects a value passing in the id selected as well as the row the autocomplete is on (this function then updates a hidden field in the same row, using the values passed in, with the ID). The function looks like so: -
function updateHiddenInput(id, num){
var objID = "objectID[" + num + "].id";
$(document.getElementById(objID)).val(id);
}
Everything works until I add a new row within my table, this pushes everything down one row and stops the autocomplete from updating the right rows hidden field (as its still referencing the old row).
Currently I have another piece of code that goes through and renames all the fields when a new row is inserted, but I have no idea how to update the autocomplete so that it passes through the right row number, anyone know how I can alter this?
The only other alternative I could think of would be to just pass through the object itself as well as the ID I can then locate the hidden based off the object, but I can't work out how to do this, any suggestions gratefully received! :S
I've tried changing
onItemSelect="updateHiddenInput(id,${newRow-1})"
to
onItemSelect="updateHiddenInput(id,this)"
Theoretically so I can just pass through the autocomplete object and from there just traverse the page to find the hidden field I want to update. However when I then attempt to use that object in my function, for example with something like: -
var mynumber = $(myobject).closest('td').find('input').val();
I always get an "undefined" returned when I try to alert back the value...
If I just put in an alert(myobject) in the function it returns AutoComplete instance0 autoLook[0].id but if I've inserted new lines the id value doesn't change (i.e the objects id is now autoLook[3].id but it still shows [0], which I think could be part of the problem but I've got now idea how I can update this value...
I notice when looking in firebug at the html there is a /script linked to the autocomplete which could be the problem as this doesn't get updated when new lines are added and I can see multiple references to the old/original id value (see below) so maybe the passing through of this isn't passing the current objects values through...?
<script type="text/javascript">
var autoCompleteDataSource = new YAHOO.util.XHRDataSource("/Framework/object/searchAJAX");
autoCompleteDataSource.responseType = YAHOO.util.XHRDataSource.TYPE_XML;
autoCompleteDataSource.responseSchema = {
resultNode : "result",
fields : [
{ key: "name" },
{ key: "id" }
]
};
;
autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','ad186a42e45d14d5cde8281514f877e42', autoCompleteDataSource);
autoComplete.queryDelay = 0;
autoComplete.prehighlightClassName = 'yui-ac-prehighlight';
autoComplete.useShadow = false;
autoComplete.minQueryLength = 3;
autoComplete.typeAhead = false;
autoComplete.forceSelection = true;
autoComplete.maxResultsDisplayed = 20;
autoComplete.shadow = false;
var itemSelectHandler = function(sType, args) {
var autoCompleteInstance = args[0];
var selectedItem = args[1];
var data = args[2];
var id = data[1];
updateHiddenInput(id,this) };
autoComplete.itemSelectEvent.subscribe(itemSelectHandler);
</script>
My thanks so far to user1690588 for all his help thus far! :)
On further digging I'm convinced that my issues is down to the line autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','a5b57b386a2d1c283068b796834050186', autoCompleteDataSource); specifically the part where its inputting autoLook[].id and if I could change this I'd then be ok, but this line is auto generated and I've got no idea how to update it, anyone have any similar experience?
I have not much idea about your gsp page but I tried it on my side:
My gsp:
<!DOCTYPE html>
<html>
<head>
<resource:autoComplete skin="default"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = ${list.size()};
function asd() {
jQuery.ajax({
url: " ${createLink(controller: 'oauthCallBack', action: 'testAuto')}",
data: "idx=" + counter++,
success: function (data) {
jQuery("#tableId").append("<tr><td>" + data + "</td></tr>");
}
});
}
function updateHiddenInput(id, tg) {
jQuery(tg).val(id);
}
</script>
</head>
<body>
<g:form>
<table id="tableId">
<g:each in="${list}" var="vr" status="idx">
<tr>
<td>
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
</td>
</tr>
</g:each>
</table>
</g:form>
<button onclick="asd()">Add</button>
</body>
</html>
My action:
def testAuto() {
render template: 'addNew', model: [idx: params.idx]
}
My template(addNew):
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}"
onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
Try this..,.
EDIT.....................................................................................
I supposed that you have successfully updated all the input field names. Then you can edit hidden field like:
View:
<tr class="dummyClass">
<td>
<richui:autoComplete name="name[${idx}]" id="uniqueId[${idx}]" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, this)"/>
<g:hiddenField name="someName[${idx}]" id="someId[${idx}]" value=""/>
</td>
</tr>
jQuery:
function updateHiddenInput(id, tg) {
jQuery(tg._elTextbox).closest("tr.dummyClass").find("input[type=hidden]").val(id);
}
EDIT.....................................................................................
Why you need to change the 'id'? Changing name is sufficient to send values in order. And you can update the hidden field without id as above edit.
If you still need to change the id then you can change it by cloning the tr and then use regex. See this answer for full working example.

Check a user input value against values in array

I have text file. there around 1000 lines in it, each line contains a 8 letter alpha numeric word for example my text file looks like this
TEST1234
T1E2A334
12RR8912
and so on. this file is located on the server in a folder called TestCodes
Now I have an html file called test.html where in this file I have input textbox where the user enters the testcode he/she has with them
I have button called Verify. when this input button is clicked I want to check the user inputed value against the contents in the text file.
If the testcode exists in the text file then display a button called Procced if not display an error message called invalid.
I know how to write the if condition but I have no idea how to check it against the text file
HTML
<div class="user-input">
<input type="text" name="test-code" id="test-code" value="" />
<input type="submit" value="Verify Code" name="verify-code" id="verify-code" />
</div>
<div id="TestRegister">
<form id="club" action="/Proceed.html" method="post" autocomplete="off">
<input type="submit" value="Proceed Registration" name="proceed-register" />
</form>
</div>
<div id="TestError">
<span>Please check the code again, its not valid</span>
</div>
JavaScript
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#TestRegister").hide();
$("#TestError").hide();
$.get("testcodes.txt", function (data) {
var lines = data.split("\n");
// this is where I am stuck. how to pass the above to ARRAY
$("#verify-code").click(function (e) {
e.preventDefault();
if ( /* here I need to check against the user input value, if they are equal */ ) {
$("#TestRegister").show();
$("TestError").hide();
} else {
$("#TestRegister").hide();
$("TestError").show();
}
}
});
</script>
How can I pass text from testcodes to an Array and then check the user input value against this array? If the user input value is present in the array then I want to show #TestRegister, and if not, or if the input value is blank or null, show #TestError.
Thanks and appreciate any tips.
var lines;
$(document).ready(function () {
$("#TestRegister").hide();
$("#TestError").hide();
$.get("testcodes.txt", function (data) {
lines = data.split("\n");
});
$("#verify-code").click(function (e) {
e.preventDefault();
if (lines.indexOf($("#test-code").val()) !== -1 && $("#test-code").val().length == 8) {
$("#TestRegister").show();
$("TestError").hide();
} else {
$("#TestRegister").hide();
$("TestError").show();
}
});
});
You can avoid an array loop altogether by creating a regular expression that ensures the test code is found between word boundaries:
var codeRegEx = new RegExp('\\b'+$('#test-code').val()+'\\b');
if(codeRegEx.test(lines)) {
// the testcode is found on a single line, avoiding partial matches
}
Here's a demo:
jsFiddle DEMO

Categories

Resources