Populate form after mySQL query with javascript - 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)
});
}
});
});

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.

JavaScript HTML Rendering Out of Sync -- Spring MVC Project

I have a dashboard site in the works, and it makes use of SpringMVC, FusionCharts, and Bootstrap (to give an architectural overview). When I freshly start up the Tomcat server, the very first time I'm served the index page, a panel of buttons will not render properly. I get the correct number of white circles with question marks as made in the first of 3 javascript functions. If I refresh the page, the intended red and green results immediately come up, generated by the second script function.
As a preamble, the panel with buttons on it is correctly generated with the right count, correct names, correct HREFs and all else. The colors just do not change until the page is refreshed. Back when this project was first constructed, the data was being gathered via http request server-side. It was comparably slow to what is occurring now: loading the data from a file server-side and sending it through in the same format. The old way always produced the correct colors and icons after a 10-second wait. Now, the buttons just remain blank white until I refresh the page, and then I get the right results.
I believe this is just the result of two Javascript functions stepping on each other, even though I know JavaScript is single-threaded. If not, I'm stumped and lost.
Index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Free Bootstrap Admin Template : Dream</title>
<!-- Bootstrap Styles-->
<link href="css/bootstrap.min.css" rel="stylesheet" />
<!-- FontAwesome Styles-->
<link href="css/font-awesome.css" rel="stylesheet" />
<!-- Morris Chart Styles-->
<link href="js/morris/morris-0.4.3.min.css" rel="stylesheet" />
<!-- Custom Styles-->
<link href="css/custom-styles.css" rel="stylesheet" />
<!-- Google Fonts-->
<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />
<script type="text/javascript" src="js/fusioncharts/core/fusioncharts.js"></script>
<script type="text/javascript" src="js/fusioncharts/themes/fusioncharts.theme.fint.js"></script>
</head>
<body>
...
<!-- this is where the button panel is correctly created on every load
but only correctly modified on the 2nd load and later -->
<div class="row"> <div id="AppStatusTable"></div> </div>
...
<script src="js/jquery-1.10.2.js"></script>
<!-- Bootstrap Js -->
<script src="js/bootstrap.min.js"></script>
<!-- Metis Menu Js -->
<script src="js/jquery.metisMenu.js"></script>
<!-- Morris Chart Js -->
<script src="js/morris/raphael-2.1.0.min.js"></script>
<script src="js/morris/morris.js"></script>
<!-- Custom Js -->
<!--
<script src="js/custom-scripts.js"></script> -->
<script>
$(document).ready(function(){
$.get("/buttoninfo", function(data, status) {
tableMaker(data, "AppStatusTable");
});
$.get("/appstatus", function(data, status) {
appStatus(data);
});
$.get("/stackstatus", function(data, status) {
stackUpdater(data);
});
});
</script>
</body>
These last 3 functions fill out the html of a panel to contain a dynamic number of buttons, modify the inner html of those buttons, and then update other panels. The third currently takes a while and always produces correct results. I don't suspect it is the issue.
dashboard.js
function templateLoader(appTag) {
//$.get('/app/' + appTag);
window.location = "/app/" + appTag;
}
function appStatus(data){
for(var i = 0; i < data.length; ++i) {
if(data[i][1] == "up"){
$("#" + data[i][0] + "-appcheck").removeClass("btn-default");
$("#" + data[i][0] + "-appcheck").addClass("btn-success");
$("#" + data[i][0] + "-appcheck-icon").removeClass("fa-exclamation-circle");
$("#" + data[i][0] + "-appcheck-icon").addClass("fa-check");
} else if(data[i][1] == "down"){
$("#" + data[i][0] + "-appcheck").removeClass("btn-default");
$("#" + data[i][0] + "-appcheck").addClass("btn-danger");
$("#" + data[i][0] + "-appcheck-icon").removeClass("fa-exclamation-circle");
$("#" + data[i][0] + "-appcheck-icon").addClass("fa-close");
}
}
}
function tableMaker(data, tableID) {
/* vars used below as the skeleton of the injected buttons*/
var i = 0, j = 0, colLimit = 12;
for(; i < data.length;){
for (var j = 0; j < colLimit && i < data.length; ++j, ++i) {
mytable += colStart + data[i][2] + titleEnd + '\n' + buttonStart + data[i][2] + buttonMiddle1 +
data[i][2] + buttonMiddle2 + data[i][2] + buttonMiddle3 + '><i id="' + data[i][2] +
buttonEnd + colEnd;
}
}
panel += mytable + panelEnd;
document.getElementById(tableID).innerHTML = panel;
}
function stackUpdater(data){
for(var i = 0; i < data.length; ++i){
var curStack = data[i][0];
for(var j = 1; j < data[i].length; j++) {
if(data[i][j] == null) {
break;
} else {
$("#" + curStack + j).removeClass("progress-bar-info");
if(data[i][j] == "up") {
$("#" + curStack + j).addClass("progress-bar-success");
} else {
$("#" + curStack + j).addClass("progress-bar-danger");
}
}
}
}
}
I understand browsers cache the results of javascript functions, but the third function is run on every refresh, so why wouldn't the first two be? And thus, why would the results of the second function only appear after refreshing?
What needs to be changed to make sure the buttons modify correctly the FIRST time this page is loaded?
UPDATE 1
After inserting alerts between the function calls, the rendering works on the first try, so what's the correct way to ensure synchronization without this?
Bottom of Index.html:
$(document).ready(function(){
$.get("/buttoninfo", function(data, status) {
tableMaker(data, "AppStatusTable");
});
alert("Button table made!");
$.get("/appstatus", function(data, status) {
appStatus(data);
});
alert("Button Data Updated!");
$.get("/stackstatus", function(data, status) {
stackUpdater(data);
});
alert("Stack Data Updated!");
});
</script>
Instead of using $.get try using $.ajax with cache set to false. If $.get is absolute necessary try adding a timestamp with each request. You may refer to How to set cache: false in jQuery.get call.
Hope that help.

Correct way to append data into existing data table using ajax

Introduction
I am working with the functions where user search donor organizations by name.
Data loads in DataTable, paging enabled and works fine for the initial data load.
(Data load with initial call from jquery is about 100 records)
Lately, i have tried to implement the ajax method, which is suppose to load "next 100 records" and append to the existing records(now record reaches at 200 aprox).
Problem
Record loading on ajax call is loaded into datatable but displays this recent record on current page(no paging applied on it).
When user change the page to navigate between records, this recent record disappear.
I am just manipulating DOM elements, i think i have to pass it to datatable, yes?
Complete Code(just copy and paste whole code to test,cdn libs used)
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<head>
<title>Demo : Test</title>
<!-- Meta -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3">
<form>
<input type="text" id="searchParam" name="searchParm" placeholder="enter search param">
<br>
<input type="submit" value="Submit" onclick="searchDonors(document.getElementById('searchParam').value); return false;">
</form>
<br />
</div>
<div class="col-md-9">
<div id="demoApim"><table id="demoApi"><thead><tr><td>Organization Name</td><td>Address</td></tr></thead><tbody id="tBody"></tbody></table></div>
</div>
<div class="col-md-3" id="searchBtn"><input type="submit" value="Load Next 100 Records" onclick="loadNext(); return false;"></div>
</div>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
var count;
$('#searchBtn').hide();
$(document).ready(function () { $('table').hide();});
function searchDonors(searchParam) {
window.searchDonorsParam = searchParam;
count = 100;
var request = new XMLHttpRequest();
request.open("GET", "http://graphapi.firstgiving.com/v1/list/organization?q=organization_name:" + searchParam + "*%20AND%20country:US&&page_size=100&page=1", false);
request.send();
var xml = request.responseXML;
//$.each(xml, function (key, val) {
var oName = xml.getElementsByTagName("organization_name");
//console.log(oName);
var oAddress = xml.getElementsByTagName("address_line_1");
var counts = xml.getElementsByTagName("organization_name").length;
for (var i = 1; i < counts; i++) {
var html = [];
html.push('<tr><td>', oName[i].innerHTML)
html.push('</td><td>', oAddress[i].innerHTML)
html.push('</td></tr>')
$("#tBody").append(html.join(''));
}
$('#demoApi').DataTable();
$('table').show();
$('#searchBtn').show();
//});
//console.log(oName);
//console.log(oAddress);
}
function loadNext()
{
if (count = 100)
{
$.ajax({
url: "http://graphapi.firstgiving.com/v1/list/organization?q=organization_name:" + searchDonorsParam + "*%20AND%20country:US&&page_size=100&page=2",
method: "GET",
dataType: "xml",
success: function (xml) {
var xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
console.log(xml.getElementsByTagName("organization_name"));
var oNameMore = xml.getElementsByTagName("organization_name");
var oAddressMore = xml.getElementsByTagName("address_line_1");
var countsNew = xml.getElementsByTagName("organization_name").length;
var html;
for (var i = 1; i < countsNew; i++) {
html = [];
html.push('<tr><td>', oNameMore[i].innerHTML)
html.push('</td><td>', oAddressMore[i].innerHTML)
html.push('</td></tr>')
$("#tBody").append(html.join(''));
}
},
error: function () {
console.log("call failled");
}
});
}
}
</script>
</body>
</html>
If someone have idea about that problem please let me know, any kind of help or reference will be appreciated.
"I think i have to pass it to datatable, yes?". Yes. The correct way is to go through the API. Without using the API, dataTables cannot be aware of whatever changes you have made to the underlying <table> and therefore your recent records disappear :
var table; //outside your function scopes
in searchDonors() :
table = $('#demoApi').DataTable();
in loadNext() use row.add() instead of injecting markup to <tbody> :
for (var i = 1; i < countsNew; i++) {
table.row.add([oNameMore[i].innerHTML, oAddressMore[i].innerHTML]);
}
table.draw();
yes ofc modify DOM its not enought for datatables, you need to use datatables function to access data, use this:
initialize the table:
var myTable = $('#demoApi').DataTable();
then
myTable.row.add( [oNameMore[i].innerHTML,oAddressMore[i].innerHTML] );
all the data are stored inside datables settings object,
updating the DOM don't change the current table settings so you will
lose you change after any table redraw ( search, change page, ecc.. )

Displaying multiple user outputs using JavaScript

I am trying to display multiple user outputs, so that when something is entered in the text field, it is captured and displayed in the div.
At the moment it keeps overwriting with the new result rather than adding to what is already displayed.
Can anyone help with this?
HTML:
<!DOCTYPE HTML>
<html lang="en">
<!-- more meta data needs to go in here -->
<head>
<script type="text/javascript" src="main_app_javascript.js"></script>
<link rel="stylesheet" type="text/css" href="">
<meta charset="UTF-8">
<title>List Check</title>
</head>
<body>
<input type="text" id="enter_box">
<button onclick="output_function()"> Add To List </button>
<div id="list_output"></div>
</body>
JavaScript:
function output_function() {
var user_input = document.getElementById("enter_box").value;
document.getElementById("list_output").innerHTML = user_input;
}
Do
document.getElementById("list_output").innerHTML += user_input + '<br />';
instead.
This will concatenate your value and add a line break at the end of the text, to create a "list". Notice the =+ and + '<br /> differences.
You could also try this
function output_function() {
'use strict';
var user_input = document.getElementById("enter_box").value;
var list_output = document.getElementById("list_output");
if( list_output.innerHTML === '' ) {
list_output.innerHTML = '<p>' + user_input + '</p>';
} else {
list_output.innerHTML += '<p>' + user_input + '</p>';
}
}

Getting the Value from an editable row

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
}
});

Categories