Getting the Value from an editable row - javascript

I am working on an application where I need to update the the table cell value So I make that table column editable as below.
I am getting these values from the stackMob database(cloud) .Now I want to Update this Device-nickname(editable table column) from the front-end as from the picture. You can see I am getting the Device-nickname as Undefined. So i want to put the name as I want (as I put alpesh for 352700051252111) .Now when editing is done I means when I complete the editing for first row then I want to call a function which will update the Device-nickname for the correspondence IMEI .
For printing and growing the list I used:
for(var i=0; i<=count; i++)
{
$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td><div contenteditable >"+array[i].device_nickname+"</div></td><tr>");
}
Now My question is:
How can I call a function to update the values when the editing is done for each row. and How can I get the IMEI of that in which editing got done and i want to get also the value after editing of Device-nickname
thanks in advance !!!
full code is
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Dashboard</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://static.stackmob.com/js/stackmob-js-0.8.0-bundled-min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<link rel="stylesheet" href= "http://code.jquery.com/ui/1.10.2/themes/dark-hive/jquery-ui.css" />
<!-- <link rel="stylesheet" href= "http://code.jquery.com/ui/1.10.2/themes/redmond/jquery-ui.css" />-->
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script type="text/javascript" src="http://twitter.github.com/bootstrap/assets/js/bootstrap-modal.js"></script>
<script type="text/javascript" src="style/js/bootstrap.js"></script>
<script type="text/javascript" src="path_to/jquery.js"></script>
<script type="text/javascript" src="path_to/jquery.simplePagination.js"></script>
<link type="text/css" rel="stylesheet" href="path_to/simplePagination.css"/>
<link type="text/css" rel="stylesheet" href="style/css/bootstrap.css"></link>
<script type="text/javascript">
/* <![CDATA[ */
// Initialize StackMob object
// Copy your init data from here: https://dashboard.stackmob.com/sdks/js/config
// Your other app information is here: https://dashboard.stackmob.com/settings
StackMob.init({
appName: "swara_sangam",
clientSubdomain: ".........",
publicKey: "....",
apiVersion: 0
});
/* ]]> */
</script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function() {
result();
function result() {
var device = StackMob.Model.extend({ schemaName: 'device' });
var mydevice = new device({organization_id:'1' });
var q = new StackMob.Collection.Query();
//q.lt('age', 50)..orderAsc('username');
q.setRange(0,15).orderDesc('lastmoddate');
mydevice.query(q, {
success: function(modal) {
//After StackMob returns "Bill Watterson", print out the result
var array = modal.toJSON();
// console.debug(array);
//$('#data').html(array[0].user_name);
var val = array[0].lastmoddate;
$('#last_mod_date').attr('value', val);
var key;
var count = 0;
for(key in array) {
if(array.hasOwnProperty(key)) {
count ++;
}
}
//alert(count);
for(var i=0; i<=count; i++)
{
// if(array[i].org_img == localStorage.getItem("stackmob.oauth2.user"))
//alert(array[i].org_img);
//$('#last_mod_date').html(array[0].lastmoddate);
//alert(val);
$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td ><div class="device-name" contenteditable>"+array[i].device_nickname+"</div></td><td>"+array[i].device_org+"</td><td>"+ new Date(array[i].lastmoddate)+"</td><tr>");
//alert("save");
//$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td><div class='divEditable' contenteditable='true' data-orig='"+array[i].device_nickname+"' >"+array[i].device_nickname+"</div></td><tr>");
alert("save");
//end if condition
} // end for loop
$('.device-name').on('blur', function(event){
alert(event.target.textContent);
alert($(event.target).closest('tr').find('.imei').text());
alert($(event.target).closest('tr').find('.model').text());
})
} //end success
}); // end imagesearch schema query
} // end result function
setInterval(check_newentry,1000);
function check_newentry() {
var device = StackMob.Model.extend({ schemaName: 'device' });
var mydevice = new device({ });
var q = new StackMob.Collection.Query();
q.orderDesc('lastmoddate');
mydevice.query(q, {
success: function(modal) {
//After StackMob returns "Bill Watterson", print out the result
var array = modal.toJSON();
// console.debug(array);
//$('#data').html(array[0].user_name);
// alert(lastmod_date_old +"..."+ lastmod_date);
if(lastmod_date_old < lastmod_date)
{
var val = array[0].lastmoddate;
$('#last_mod_date').attr('value', val);
var key;
var count = 0;
var counter=0;
for(key in array) {
if(array.hasOwnProperty(key)) {
count ++;
}
}
//alert(count);
for(var i=0; i<=count; i++)
{
$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td>"+array[i].device_nickname+"</td><td>"+array[i].device_org+"</td><td>"+new Date(array[i].lastmoddate)+"</td><tr>");
//------------------------------------------- end device schema code
counter++;
exit();
}
}
}
});
}
});
</script>
</head>
<body>
<div class="modal-body" style=''>
<table class="data table-bordered table table-striped" id="ui" >
<tr style="background-color:blue;color:white;"><td width="25%">Device-imei</td><td>Device-Model</td><td>device-nickname</td><td>Device-org</td><td>Time</td></tr>
</table>
</div>
<!--<div id="last_mod_date" value=""></div>
<div id="latlng" value=""></div> -->
</script>
</body>
</html>

$('.device-name').on('blur', function(event){
alert(event.target.textContent);
alert($(event.target).closest('tr').find('.imei').text());
alert($(event.target).closest('tr').find('.model').text());
})
See http://jsfiddle.net/Jke9J/3/
To get other data you can assign classes for each column, get closest tr after data was changed, and find data by these classes inside found tr
Edit:
See http://jsfiddle.net/Jke9J/7/

SCRIPT:
var editable = document.querySelectorAll('div[contentEditable]');
for (var i=0, len = editable.length; i<len; i++){
editable[i].setAttribute('data-orig',editable[i].innerHTML);
editable[i].onblur = function(){
if (this.innerHTML == this.getAttribute('data-orig')) {
// no change
}
else {
// change has happened, store new value
this.setAttribute('data-orig',this.innerHTML);
}
};
}
Copied from onChange event with contenteditable
You can simplify the above code like
for(var i=0; i<=count; i++)
{
$("#ui").append("<tr><td>"+array[i].device_IMEI+"</td> <td>"+array[i].device_model+"</td><td><div class='divEditable' contenteditable='true' data-orig='"+array[i].device_nickname+"' >"+array[i].device_nickname+"</div></td><tr>");
}
$(document).on('blur','.divEditable',function(){
if($(this).html()!=$(this).data('orig'))
// innnerHTML is changed then reassign the data-orig attr
{
$(this).data('orig',$(this).html());
// code to get closest imei for that row
imei=$(this).closest('tr').find('td:first-child').html();
console.log(imei);// to test
}
});

Related

How to create a button that calls a function and passes parameters in jQuery?

I am trying to create a button in jQuery which has a onClick event and which calls a function and passes some parameters. Here is what I tried so far :
var user_array = [];
user_array['recipient_name'] = recipient_name.value;
user_array['co_name'] = co_name.value;
var myTable = $('#myTable').DataTable();
var rowNode = myTable.row.add(['<button type="button" id="button_edit" onclick=edit_customer_request(1,user_array)"name="edit_customer">Edit</button>'
])
.draw()
As you can see I am adding a new row in the table which has a button. I am able to create the button, so, it displays. However, it doesn't work, it doesn't call that function onclick. Pay attention to the parameters, I am trying to pass two parameters, first one is just a number and the second is an array : onclick=edit_customer_request(1,user_array)
EDIT. Screenshot:
I may have misunderstood the request, but here is what I think you are trying to do.
Here is a self-contained solution you can run for yourself:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="myTable" class="display dataTable cell-border" style="width:100%">
<thead>
<tr><th>Foo</th></tr>
</thead>
</table>
</div>
<script type="text/javascript">
var recipient_name = { "value": "Jon Smith" };
var co_name = { "value": "Starbucks" };
var user_obj = {};
user_obj['recipient_name'] = recipient_name.value;
user_obj['co_name'] = co_name.value;
function edit_customer_request(id, data) {
data_obj = JSON.parse(data);
console.log("In the function!");
console.log("ID: " + id);
console.log("recipient name: " + data_obj['recipient_name']);
console.log("co. name: " + data_obj['co_name']);
}
$(document).ready(function() {
var myTable = $('#myTable').DataTable();
var btnHtml = '<button type="button" id="button_edit" onclick="edit_customer_request(1, JSON.stringify(user_obj))" name="edit_customer">Edit</button>';
var rowNode = myTable.row.add( [ btnHtml ] ).draw();
} );
</script>
</body>
</html>
When you click the button, the edit_customer_request function is called, and it logs the following messages to the console (using my sample data):
In the function!
ID: 1
recipient name: Jon Smith
co. name: Starbucks
Some points to note:
I changed your var user_array = []; to this: var user_obj = {}; because I think you need an object here, not an array.
The code uses JSON.stringify() to convert an object into text, so it can be passed as a parameter to the function - and then converted back to an object using JSON.parse().
I took a guess at some sample data to make the demo run.

edit button input should be listed after clicking anything other on page

i made a to-do list and i am very new at this , but after adding multiple task it is adding in incomplete task and have one edit and delete button when trying to edit any list it is converting in type= text but when entering outside of this edit task it is still open to edit it should not be happening
here is java script code
var taskInput=document.getElementById("new-task");
var addButton=document.getElementsByTagName("button")[0];
var incompleteTaskHolder=document.getElementById("incomplete-tasks");
var completedTasksHolder=document.getElementById("completed-tasks");
var createNewTaskElement=function(taskString){
var listItem=document.createElement("li");
var checkBox=document.createElement("input");
var label=document.createElement("label");
var editInput=document.createElement("input");
var editButton=document.createElement("button");
var deleteButton=document.createElement("button");
label.innerText=taskString;
checkBox.type="checkbox";
editInput.type="text";
editButton.innerText="Edit";
editButton.className="edit";
deleteButton.innerText="Delete";
deleteButton.className="delete";
listItem.appendChild(checkBox);
listItem.appendChild(label);
listItem.appendChild(editInput);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
return listItem;
}
var addTask=function(){
console.log("Add Task...");
if(taskInput.value==='')
{
alert('Required');
}
else
{
var listItem=createNewTaskElement(taskInput.value);
incompleteTaskHolder.appendChild(listItem);
bindTaskEvents(listItem, taskCompleted);
taskInput.value="";
}
}
var editTask=function(){
console.log("Edit Task...");
console.log("Change 'edit' to 'save'");
var listItem=this.parentNode;
var editInput=listItem.querySelector('input[type=text]');
var label=listItem.querySelector("label");
var containsClass=listItem.classList.contains("editMode");
if(containsClass){
if(listItem.value=='')
{
alert('empty edit');
}
else
{
label.innerText=editInput.value;
}
}else{
editInput.value=label.innerText;
}
listItem.classList.toggle("editMode");
}
var deleteTask=function(){
console.log("Delete Task...");
var listItem=this.parentNode;
var ul=listItem.parentNode;
ul.removeChild(listItem);
}
var taskCompleted=function(){
console.log("Complete Task...");
var listItem=this.parentNode;
completedTasksHolder.appendChild(listItem);
bindTaskEvents(listItem, taskIncomplete);
}
var taskIncomplete=function(){
console.log("Incomplete Task...");
var listItem=this.parentNode;
incompleteTaskHolder.appendChild(listItem);
bindTaskEvents(listItem,taskCompleted);
}
var ajaxRequest=function(){
console.log("AJAX Request");
}
//addButton.onclick=addTask;
addButton.addEventListener("click",addTask);
addButton.addEventListener("click",ajaxRequest);
$addNewTask.addEventListener("keypress",addTask);
var bindTaskEvents=function(taskListItem,checkBoxEventHandler){
console.log("bind list item events");
var checkBox=taskListItem.querySelector("input[type=checkbox]");
var editButton=taskListItem.querySelector("button.edit");
var deleteButton=taskListItem.querySelector("button.delete");
editButton.onclick=editTask;
deleteButton.onclick=deleteTask;
checkBox.onchange=checkBoxEventHandler;
}
for (var i=0; i<incompleteTaskHolder.children.length;i++){
bindTaskEvents(incompleteTaskHolder.children[i],taskCompleted);
}
for (var i=0; i<completedTasksHolder.children.length;i++){
bindTaskEvents(completedTasksHolder.children[i],taskIncomplete);
}
and here is html code where i am adding javascript
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Todo App</title>
<link rel="stylesheet" href="{{asset('css/style.css')}}">
<link rel="stylesheet" href="style.css" type="text/css" media="screen" charset="utf-8">
</head>
<body>
<div class="container">
<p>
<label for="new-task">Add List</label><input id="new-task" type="text" placeholder="Enter to do list"><button class="btn btn-default">Add</button>
</p>
<h3>To-do List</h3>
<ul id="incomplete-tasks">
</ul>
<h3>Completed Task</h3>
<ul id="completed-tasks">
</ul>
</div>
<script type="text/javascript" src="app.js"></script>
<script src="{{asset('js/index.js')}}"></script>
</body>
</html>
and here is attaching a image in which two edit input are showing and i want to when trying to do click anything other then edit should be listed , please help me
answer for your question in title
you should add id or unique identifier to that button and.
$(document).ready(()=>{
$(document.body).click((e)=>{
var button = $('#your_button_id')
if(e.target.id !== 'your_button_id' && $.contains(button[0]), e.target))
{
doSomething()
}
})
})

Populate form after mySQL query with javascript

I'm trying to do this thing:
I have a html input textbox, some php code that makes a query on my database and return a JSON element, and in the end some javascript that I cannot figure to work the right way.
I simply want to do a live search while user is typing, than select one of the record found from the live search and populate a form with data of this record.
Probably there is a very simple solution, but I'm a newbie.
This is my html and Javascript code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>InChiaro Ticket Admin</title>
<meta name="description" content="The HTML5 Herald" />
<meta name="author" content="SitePoint" />
<link href="../assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<link href="../assets/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" />
<link href="../assets/bootstrap/css/bootstrap-fileupload.css" rel="stylesheet" />
<link href="../assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
<link href="css/style-responsive.css" rel="stylesheet" />
<link href="css/style-default.css" rel="stylesheet" id="style_color" />
<link href="../assets/fullcalendar/fullcalendar/bootstrap-fullcalendar.css" rel="stylesheet" />
<link href="../assets/jquery-easy-pie-chart/jquery.easy-pie-chart.css" rel="stylesheet" type="text/css" media="screen" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<div id="main-content">
<div class="wrapper-principale">
<div class="input-append search-input-area">
<input type="text" class="search-filter" id="searchcodiceCliente" name="codiceCliente" placeholder="Cerca un cliente..." /> <!-- text AREA CODICE CLIENTE-->
<button class="btn" type="button"><i class="icon-search"></i> </button>
</div>
<div id="result" style="display:none">
<table id="tablesearch"></table>
</div>
<form>
<input type="text" id="CodiceCliente" />
<input type="text" id="denominazione" />
</form>
</div>
</div>
<script type="text/javascript">
$(function () {
// We add the event on the class, which both inputs have
$(".search-filter").keyup(function () {
// Now we get the values from both inputs, using their ID's
var codiceCliente = $("#searchcodiceCliente").val();
//var fname = $("#searchfname").val();
// Add both to the dataString (and URI encode the strings)
var requestCodCliente = "get_codiceCliente_json"
var json;
// Check that at least one has any content
if (codiceCliente != '')
$.ajax({
type: "POST",
url: "ajax_requests.php",
data: {
request: requestCodCliente,
searchCliente: codiceCliente
},
success: function (result) {
var x = document.getElementById("result");
x.style.display = "inline";
document.getElementById("tablesearch").innerHTML = '';
var th = "<tr><th></th><th>Codice Cliente</th><th>Denominazione</th><th>Indirizzo</th><th>Città</th><th>CAP</th><th>Numero Telefono</th></tr>";
document.getElementById("tablesearch").innerHTML += th;
function populateForm() {
document.getElementById("CodiceCliente").value = result[index].codiceCliente;
}
for (var index = 0; index < result.length; ++index) {
var t = "";
var tr = "<tr>";
tr += "<td><button id='select' class='btn'type='button' onclick='populateForm()'><i class='icon-search'></i></button></td>";
tr += "<td>"+result[index].codiceCliente+"</td>";
tr += "<td>"+result[index].denominazioneCliente+"</td>";
tr += "<td>"+result[index].indirizzo+"</td>";
tr += "<td>"+result[index].citta+"</td>";
tr += "<td>"+result[index].CAP+"</td>";
tr += "<td>"+result[index].numeroTelefono+"</td>";
tr += "</tr>";
t += tr;
document.getElementById("tablesearch").innerHTML += t;
}
}
});
});
});
</script>
</body>
</html>
And this is some sample output that I hope explains what I mean:
Codice cliente denominazione
c00106 Paolo re
c00116 viglino arturo
c00126 sellaro giuseppe
c00146 accusani fabio
c00161 franconi srl
Thank You
The aspect you are struggling with most is the attachment of populateForm as a click handler. As it stands, onclick='populateForm() won't work because populateForm would need to be a global member, and it's good practice not to pollute the global namespace.
To overcome this, click handling can be delegated to ancestor element of the buttons'; the <table> element is the most obvious choice. Fortunately, jQuery has a very convenient syntax for event delegation.
In addition, there is an issue you are probably not aware of; namely that multiple quick-fire AJAX requests will not necessarily respond in the expected order. On the assumption that order matters, a simple mechanism is available to ensure that table entries are in the expected order. All you need to do is :
when each AJAX request is made, synchronously append a <tbody> element.
keep a reference to each appended <tbody> element (in a closure).
when each AJAX responses is received, append rows to the appropriate <tbody> element.
Your code should be something like this :
$(function () {
// Delegate handling of button.btn clicks to the containing table element.
// This avoids having to attach the same click handler repeatedly to buttons in dynamically generated lines.
$("#tablesearch").on('click', 'button.btn', function() {
$("#CodiceCliente").val($(this).closest('td').next('td').text());
});
$(".search-filter").keyup(function() {
var codiceCliente = $(this).val();
if (codiceCliente != '') {
var $tbody = $('<tbody/>').appendTo("#tablesearch"); // Synchronously append a <tbody> to receive two asynchrously generated <tr>s (see below).
$.ajax({
'type': 'POST',
'url': 'ajax_requests.php',
'data': {
'request': 'get_codiceCliente_json',
'searchCliente': codiceCliente
},
}).then(function (result) {
$("#result").css('display', "inline");
$("<tr><th></th><th>Codice Cliente</th><th>Denominazione</th><th>Indirizzo</th><th>Città</th><th>CAP</th><th>Numero Telefono</th></tr>").appendTo($tbody); // append to the correct <tbody> for this response
for (var i = 0; i < result.length; ++i) {
$("<tr><td><button class='btn'><i class='icon-search'></i></button></td><td>" +
result[i].codiceCliente + "</td><td>" +
result[i].denominazioneCliente + "</td><td>" +
result[i].indirizzo + "</td><td>" +
result[i].citta + "</td><td>" +
result[i].CAP + "</td><td>" +
result[i].numeroTelefono + "</td></tr>").appendTo($tbody); // append to the correct <tbody> for this response
}
}, function() {
$tbody.remove(); // ajax failed so no point keeping the <tbody> element (unless you want to display an error message in the table)
});
}
});
});

variable undefined Jquery socket.io

I have a table with the following data.
description
object 1
object 2
object 3
I try to get this data from my database via socket.io and put the data into a string variable called Objects. The string Objects will look like this object1,object2,object3.
If I try to do alert(objects) the string is undefined.
My HTML code is
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>SlickGrid example 1: Basic grid</title>
<link rel="stylesheet" href="/slick.grid.css" type="text/css"/>
<link rel="stylesheet" href="/css/smoothness/jquery-ui-1.8.16.custom.css" type="text/css"/>
<link rel="stylesheet" href="/examples/examples.css" type="text/css"/>
</head>
<body>
<script src="/lib/jquery-1.7.min.js"></script>
<script src="/lib/jquery.event.drag-2.2.js"></script>
<script src="../lib/jquery-ui-1.8.16.custom.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
var objects;
var temp=[];
socket.on('load data', function(data){
for (var i = 0; i < data.length; i++) {
temp = data[i];
objects = objects + "," + temp.description;
};
objects = objects.substr(10, objects.length-10);
objects=$.trim(objects);
});
alert(objects); <== undefined
})
</script>
</body>
</html>
I tried document ready (see here below) since alert(objects) is executed before the socket.io, but this doesn't help.
$( document ).ready(function() {
alert(objects);
});
How should I solve this issue?
Thank you for your time!!
You should consider using the socket.io debugging tool inside of the chrome debugger.
$(function(){ // don't pass $ as an argument to this function
var socket = io.connect(), // what are you connecting to?
objects,
temp=[];
socket.on('load data', function(data){
for (var i = 0; i < data.length; i++) {
temp = data[i];
objects = objects + "," + temp.description;
};
objects = objects.substr(10, objects.length-10);
objects=$.trim(objects);
alert(objects); // what is the value of objects here?
});
alert(objects); // socket.on is asynchronous so this line is will pretty much always
// be executed before your callback function for socket.on()
});

Import Excel file to a table of HTML page

I have a simple Excel file in my computer at "D:/Book1.xls". I want to import it to make a table and append the table to a div tag in my HTML page.
Would you modify my code below?
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<style type="text/css">
</style>
<script src='http://alasql.org/console/alasql.min.js'></script>
<script src='http://alasql.org/console/xlsx.core.min.js'></script>
<script src="./libs/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alasql('select * into html("#res",{headers:true}) \
from xlsx("d:/Book1.xls",\
{headers:true})');
alert("end of function")
});
</script>
</head>
<body>
<div id="res">res</div>
</body>
</html>
The problem is you are trying to get access of file directly from web page which is not possible. You cannot access any file outside of you browser. For that you have to select the input element of html and after getting the file data you can store it to javascript variable.
<script src="alasql.min.js"></script>
<script src="xlsx.core.min.js"></script>
<p>Select CSV file to read:</p>
<input id="readfile" type="file" onchange="loadFile(event)"/>
<script>
function loadFile(event) {
alasql('SELECT * FROM FILE(?,{headers:true})',[event],function(data){
console.log(data);
// You can data to div also.
});
}
</script>
Scripts
<script src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.8.3.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/infragistics.core.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/infragistics.lob.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_core.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_collections.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_text.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_io.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_ui.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.documents.core_core.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_collectionsextended.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.excel_core.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_threading.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.ext_web.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.xml.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.documents.core_openxml.js"></script>
<script type="text/javascript" src="http://cdn-na.infragistics.com/igniteui/2018.2/latest/js/modules/infragistics.excel_serialization_openxml.js"></script>
JS
$(function () {
$("#input").on("change", function () {
var excelFile,
fileReader = new FileReader();
$("#result").hide();
fileReader.onload = function (e) {
var buffer = new Uint8Array(fileReader.result);
$.ig.excel.Workbook.load(buffer, function (workbook) {
var column, row, newRow, cellValue, columnIndex, i,
worksheet = workbook.worksheets(0),
columnsNumber = 0,
gridColumns = [],
data = [],
worksheetRowsCount;
// Both the columns and rows in the worksheet are lazily created and because of this most of the time worksheet.columns().count() will return 0
// So to get the number of columns we read the values in the first row and count. When value is null we stop counting columns:
while (worksheet.rows(0).getCellValue(columnsNumber)) {
columnsNumber++;
}
// Iterating through cells in first row and use the cell text as key and header text for the grid columns
for (columnIndex = 0; columnIndex < columnsNumber; columnIndex++) {
column = worksheet.rows(0).getCellText(columnIndex);
gridColumns.push({ headerText: column, key: column });
}
// We start iterating from 1, because we already read the first row to build the gridColumns array above
// We use each cell value and add it to json array, which will be used as dataSource for the grid
for (i = 1, worksheetRowsCount = worksheet.rows().count(); i < worksheetRowsCount; i++) {
newRow = {};
row = worksheet.rows(i);
for (columnIndex = 0; columnIndex < columnsNumber; columnIndex++) {
cellValue = row.getCellText(columnIndex);
newRow[gridColumns[columnIndex].key] = cellValue;
}
data.push(newRow);
}
// we can also skip passing the gridColumns use autoGenerateColumns = true, or modify the gridColumns array
createGrid(data, gridColumns);
}, function (error) {
$("#result").text("The excel file is corrupted.");
$("#result").show(1000);
});
}
if (this.files.length > 0) {
excelFile = this.files[0];
if (excelFile.type === "application/vnd.ms-excel" || excelFile.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" || (excelFile.type === "" && (excelFile.name.endsWith("xls") || excelFile.name.endsWith("xlsx")))) {
fileReader.readAsArrayBuffer(excelFile);
} else {
$("#result").text("The format of the file you have selected is not supported. Please select a valid Excel file ('.xls, *.xlsx').");
$("#result").show(1000);
}
}
})
});
function createGrid(data, gridColumns) {
if ($("#grid1").data("igGrid") !== undefined) {
$("#grid1").igGrid("destroy");
}
$("#grid1").igGrid({
columns: gridColumns,
autoGenerateColumns: true,
dataSource: data,
width: "100%",
});
}
HTML
<input type="file" id="input" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
<div id="result"></div>
<table id="grid1"></table>

Categories