lfetch data from table to text box - html

I am creating a table through jQuery and in this table I concatenate 3 columns in 1 column:
so how i concatenate multiple columns in 1 column
Before concatenate:
if (re.length > 0) {
$("#services_schdulue").append
$('#services_schdulue thead').append("<tr><th>Service ID</th><th>Service Type</th><th>frequency</th><th>Freq_Duration</th><th>Freq_Mileage</th></tr>");
for (var i = 0; i < re.length; i++) {
if (re[i] !== null) {
$('#services_schdulue tbody').append('<tr><td>' + re[i][0] +
'</td><td>' + re[i][1] +
'</td><td>' + re[i][2] +
'</td><td>' + re[i][3]
'</td><td>' + re[i][4] +
'</td></tr>');
}
}
}
After concatenate:
if (re.length > 0) {
$("#services_schdulue").append
$('#services_schdulue thead').append("<tr><th>Service ID</th><th>Service Type</th><th>S freq</th></tr>");
for (var i = 0; i < re.length; i++) {
if (re[i] !== null) {
$('#services_schdulue tbody').append('<tr><td>' + re[i][0] +
'</td><td>' + re[i][1] +
'</td><td>' + re[i][2] + '' + re[i][3] + '' + re[i][4] +
'</td></tr>');
}
}
}
var myTable = $('#services_schdulue').DataTable({
"columnDefs": [{
"visible": false,
"targets": [3,4,5]
}]
});

Try below solution , i think this will help you.
$('#services_schdulue').on('click', 'tr', function () {
var row = $(this)[0];
console.log(re[row._DT_RowIndex]);
});
In console you find the entire data of the row , which row you click.
As per your jsfiddle, below solution is help to you. Don't fogot to declare variable re outside of the document.ready
$('#tabledata').on('click', 'tr', function () {
$("#myModal").modal("show");
var row = $(this);
var row_index = row[0]._DT_RowIndex;
var data = re[row_index];
$("#txt_status").val(data.Status);
debugger;
//var repeat = myTable.row.find('td')[2].firstChild.data;
$("#txt_speed").val(data.Speed);
});

Related

Convert JSON data to table

I am trying to create table from my JSON data which looks like this:
It works for a specific JSON data:
var items = [
{"Name":"A","Type":2,"Result":"0"},
{"Name":"A","Type":1,"Result":"1"},
{"Name":"B","Type":2,"Result":"1"},
{"Name":"B","Type":1,"Result":"0"},
]
But, it doesn't create table correctly if the columns ("Type") is random
var items = [
{"Name":"A","Type":5,"Result":"1"}
{"Name":"A","Type":2,"Result":"0"},
{"Name":"A","Type":1,"Result":"1"},
{"Name":"B","Type":3,"Result":"1"},
{"Name":"B","Type":2,"Result":"1"},
{"Name":"B","Type":1,"Result":"0"},
]
Can someone tell me what's the issue with my code?
I want to create table for dynamic JSON data which may not have cell values for all the columns. With this code, I don't see entry in column 5 for A as 1.
function get_prop(obj, prop) {
return prop.split('.').reduce((o,k) => obj[k], obj);
}
function coll2tbl(json, row_header, col_header, cell) {
var table = {};
var row_headers = [];
var cols = {};
json.map(function(a) {
var h = get_prop(a, row_header);
if (h in table === false) {
table[h] = {};
row_headers.push(h);
}
var c = get_prop(a, col_header);
cols[c] = null;
table[h][c] = get_prop(a, cell);
});
var cells = [];
for (var row in table) {
cells.push(Object.values(table[row]));
}
console.log('row_headers' + row_headers);
console.log('Object.keys(cols)' + Object.keys(cols));
console.log('cells' + cells);
var headerRow = '<th>' + capitalizeFirstLetter('TestName') + '</th>';
var colKeys = Object.keys(cols);
colKeys.map(function(col) {
headerRow += '<th>' + capitalizeFirstLetter(col) + '</th>';
});
var bodyRows = '';
for (var i in cells) {
bodyRows += '<tr>';
bodyRows += '<td>' + row_headers[i] + '</td>';
for (var j in cells[i]) {
console.log('Processing row: ' + row_headers[i] + ' result: ' + cells[i][j] + ' i=' + i + ' j=' + j);
bodyRows += '<td>';
if (cells[i][j] === "1") {
bodyRows += '<font color="green">' + cells[i][j] + '</font>';
}
else if (cells[i][j] === "0") {
bodyRows += '<font color="red">' + cells[i][j] + '</font>';
}
else if (cells[i][j] === "-1") {
bodyRows += '<font color="orange">' + cells[i][j] + '</font>';
}
else {
bodyRows += "-";
}
bodyRows += '</td>';
}
bodyRows += '</tr>';
}
//return { row_headers, col_headers: Object.keys(cols), cells };
return ('<table> <thead><tr>' + headerRow + '</tr></thead><tbody>' + bodyRows + '</tbody></table>');
}
function capitalizeFirstLetter(string) {return
string.charAt(0).toUpperCase() + string.slice(1);
}
coll2tbl(items, 'Name', 'Type', 'Result');
My table should like like this:
Name 1 2 3 4 5
A 1 1 - - 1
B 1 1 1 - -
The answer https://stackoverflow.com/a/52199138/10320683 is of course correct, but if you need or want to stick to your specific code, you can put this below your json.map (which should by the way use forEach and not map, since you do not use the returned array anyways)
for (var col in cols) {
for (row in table) {
if (!table[row].hasOwnProperty(col)) {
table[row][col] = "-";
}
}
}
The reason why your code did not work is that by iterating over the rows, you do not get all the possible type properties, which becomes clear if you inspect your table variable: { a: {1: "1", 2: "0", 5: "1"}, b: {...}} (this is missing the 3 type property), so by calling Object.values(table[row]) later on, you get the following array for your cells: ["1", "0", "1"], but you do have 4 columns, so the "Type 5" result (1) gets shifted one column to the left.
Also, you need to be careful because your code is relying on the sorting that Object.values() produces, which means that if you want to change the order of your columns, your code would not work.

AS3 array to clean up long code?

I would like a better way to write this possibly using an array but I have been unsuccessful. See my code below. I need to add more details to post this but i can't think of more to say. I suppose I eventually need to have to set up a row of btnA show both B and C simultaneously as well. That would also be helpful.
I have a chart that either turns on a square or turns it off when clicked, for example btn3 toggles the visibility of checkMark3, works as written, but when I have 50 or 60 options of clicking the code is exhausting to write and becomes unruly
btnB1.addEventListener (MouseEvent.CLICK, showB1);
function showB1(event:MouseEvent) {
if (checkMarkB1.alpha == 1){
checkMarkB1.alpha = 0;} else {checkMarkB1.alpha = 1}
}
btnB2.addEventListener (MouseEvent.CLICK, showB2);
function showB2(event:MouseEvent) {
if (checkMarkB2.alpha == 1){
checkMarkB2.alpha = 0;} else {checkMarkB2.alpha = 1}
}
btnB3.addEventListener (MouseEvent.CLICK, showB3);
function showB3(event:MouseEvent) {
if (checkMarkB3.alpha == 1){
checkMarkB3.alpha = 0;} else {checkMarkB3.alpha = 1}
}
btnB4.addEventListener (MouseEvent.CLICK, showB4);
function showB4(event:MouseEvent) {
if (checkMarkB4.alpha == 1){
checkMarkB4.alpha = 0;} else {checkMarkB4.alpha = 1}
}
btnC1.addEventListener (MouseEvent.CLICK, showC1);
function showC1(event:MouseEvent) {
if (checkMarkC1.alpha == 1){
checkMarkC1.alpha = 0;} else {checkMarkC1.alpha = 1}
}
btnC2.addEventListener (MouseEvent.CLICK, showC2);
function showC2(event:MouseEvent) {
if (checkMarkC2.alpha == 1){
checkMarkC2.alpha = 0;} else {checkMarkC2.alpha = 1}
}
btnC3.addEventListener (MouseEvent.CLICK, showC3);
function showC3(event:MouseEvent) {
if (checkMarkC3.alpha == 1){
checkMarkC3.alpha = 0;} else {checkMarkC3.alpha = 1}
}
btnC4.addEventListener (MouseEvent.CLICK, showC4);
function showC4(event:MouseEvent) {
if (checkMarkC4.alpha == 1){
checkMarkC4.alpha = 0;} else {checkMarkC4.alpha = 1}
}
Add all your buttons to an array, and all your checkMarks to another array. Make sure that the order of the items in the array means that the position of each button in the buttons array corresponds with the position of its associated checkMark in the checkMarks array.
//add an event listener to all buttons
for(var i:uint=0; i<buttons.length; i++){
buttons[i].addEventListener(MouseEvent.CLICK, showBox);
}
//showBox function
function showBox(evt:MouseEvent):void{
for(var a:uint = 0; a<buttons.length; a++){
if (evt.target == buttons[a]){
if(checkMark[a].alpha == 1){
checkMark[a].alpha = 0;
} else {
checkMark[a].alpha = 1;
}
}
}
}
This should mean you can just add as many buttons and checkMarks as you like to the array, as long as you add them in the right order and always have a checkMark for every button.
Trex had it I just needed to get it right, this dynamically makes the names and sets the visibility of the check marks. So for a grid that has many check marks to use and turn on and off this is what I ended up with,
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.DisplayObject;
// The two parameters below will be used to dynamically generate the clipinstance names
var letters: Array = ['A', 'B', 'C', 'D', 'E'];
var index: int = 9;
for (var i: int = 1; i <= index; i++) {
// we keep a reference of the movie clip because the scope is lost in the anonymous event listener
var mc = this;
// instead of setting checkMarkE9.visible = false; we do all of this dynamically
trace('Updating visibility of : ' + 'checkMark' + letters[1] + i);
this['checkMark' + letters[1] + i].visible = false;
trace('Updating visibility of : ' + 'checkMark' + letters[2] + i);
this['checkMark' + letters[2] + i].visible = false;
trace('Updating visibility of : ' + 'checkMark' + letters[3] + i);
this['checkMark' + letters[3] + i].visible = false;
trace('Updating visibility of : ' + 'checkMark' + letters[4] + i);
this['checkMark' + letters[4] + i].visible = false;
// dynamically adding event listeners
this['btn' + letters[0] + i].addEventListener(MouseEvent.CLICK, function (e: MouseEvent) {
var btnIndex: String = getLastLetter(e.currentTarget.name);
trace('Updating visibility of : ' + 'checkMark' + letters[1] + btnIndex);
trace('Updating visibility of : ' + 'checkMark' + letters[2] + btnIndex);
trace('Updating visibility of : ' + 'checkMark' + letters[3] + btnIndex);
trace('Updating visibility of : ' + 'checkMark' + letters[4] + btnIndex);
mc['checkMark' + letters[1] + btnIndex].visible = true;
mc['checkMark' + letters[2] + btnIndex].visible = true;
mc['checkMark' + letters[3] + btnIndex].visible = true;
mc['checkMark' + letters[4] + btnIndex].visible = true;
});
// dynamically add event listeners for cells
this['btn' + letters[1] + i].addEventListener(MouseEvent.CLICK, function (e: MouseEvent) {
switchVisibility(mc['checkMark' + letters[1] + getLastLetter(e.currentTarget.name)]);
});
this['btn' + letters[2] + i].addEventListener(MouseEvent.CLICK, function (e: MouseEvent) {
switchVisibility(mc['checkMark' + letters[2] + getLastLetter(e.currentTarget.name)]);
});
this['btn' + letters[3] + i].addEventListener(MouseEvent.CLICK, function (e: MouseEvent) {
switchVisibility(mc['checkMark' + letters[3] + getLastLetter(e.currentTarget.name)]);
});
this['btn' + letters[4] + i].addEventListener(MouseEvent.CLICK, function (e: MouseEvent) {
switchVisibility(mc['checkMark' + letters[4] + getLastLetter(e.currentTarget.name)]);
});
}
// switches a display item visiblity
function switchVisibility(display: DisplayObject): void {
display.visible = !display.visible;
}
// get the last letter of a string
function getLastLetter(str: String): String {
return str.substr(str.length - 1, str.length);
}

Sort JSON data by Date/Time value

Hope someone could help with this small task. I have an array of text blocks that have a DateTime value assigned to them. I would like to publish those text blocks sorted by DateTime so that the latest updated item is always on top.
Here is the script:
function jsonCallBack(data) {
var strRows = "";
$.each(data.News, function(i, item) {
var htmlNewsBody = item["htmlNewsBody"];
var maxLength = 120
var trimmedString = htmlNewsBody.substr(0, maxLength);
trimmedString = trimmedString.substr( 0, Math.min( trimmedString.length,
trimmedString.lastIndexOf(" ") ) );
strRows += "<div id='nrNewsItem-" + i + "'>";
strRows += "<h3>" + item["txtTitle"] + "</h3>";
strRows += "<p>" + item["dtDateTime"] + "</p>";
strRows += "<p>" + trimmedString + "...</p>";
strRows += "</div>"
});
$("#printHere").html(strRows);
};
Also have a working jsFiddle with JSON data.
You can add a custom compare method:
function compare(a,b) {
if (a.dtDateTime < b.dtDateTime) {
return 1;
}
if (a.dtDateTime > b.dtDateTime) {
return -1;
}
return 0;
}
Then in your function:
function jsonCallBack(data) {
data.News.sort(compare);
....

jQuery click() each() unique?

I want to have multiple span.play without IDs which can be clicked and play some audio file.
Problem: Display the duration on only the current file $(this)
$('.play').each(function() {
$(this).append('<span class="playIcon"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/7/76/Fairytale_player_play.png/14px-Fairytale_player_play.png"></span><span class="playDur"></span>');
$(this).click(function() {
var file = this.firstChild;
if (file.paused != false) {
//+ stop all others before playing new one
file.play();
} else {
file.pause();
}
file.addEventListener("timeupdate", function() {
var len = file.duration,
ct = file.currentTime,
s = parseInt(ct % 60),
m = parseInt((ct / 60) % 60);
if (s < 10) {
s = '0' + s;
}
$(".playDur").html(' (' + m + ':' + s + ')');
if (ct == len) {
$(".playDur").html('');
}
}, false);
});
});
Test:
http://jsfiddle.net/sQPPP/
http://jsfiddle.net/sQPPP/1/ - using $(this).children( ".foo" )
You need to save .play jQuery object in a variable, as this changes within the addEventListener callback.
http://jsfiddle.net/sQPPP/2/
$('.play').each(function(index) {
var $play = $(this);
$play.append('<span class="playIcon"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/7/76/Fairytale_player_play.png/14px-Fairytale_player_play.png"></span><span class="playDur"></span>');
$play.click(function() {
var file = this.firstChild;
if (file.paused != false) {
//+ stop all others before playing new one
file.play();
} else {
file.pause();
}
file.addEventListener("timeupdate", function() {
var len = file.duration,
ct = file.currentTime,
s = parseInt(ct % 60),
m = parseInt((ct / 60) % 60);
if (s < 10) {
s = '0' + s;
}
$play.children( ".playDur" ).html(' (' + m + ':' + s + ')');
if (ct == len) {
$play.children( ".playDur" ).html('');
}
}, false);
});
});​

AS: if statement evaluating incorrectly

I have a very simple piece of logic as follows:
var divert:Number = 0;
for (var connection in _connections) {
trace("target: " + _connections[connection].target + " || i: " + (i + 1));
if(int(_connections[connection].target) != (i + 1)) {
trace("bad connection");
divert++;
}
}
The problem is that when i + 1 and int(_connections[connection].target) are equal the if statement is returning true as can be seen in the output of my trace() statements below:
target: 0 || i: 1
bad connection
target: 1 || i: 1
bad connection
Can anyone see what could be causing this to happen?
EDIT: The function this is contained in as per request:
public function loadListener(i:Number, onProgress:Function, onComplete:Function):Void
{
trace("load listening to: "+i);
trace("next in queue: " + _queues["lower"][0] + " | " + _queues["upper"][0]);
_functions[i] = {onProgress:onProgress, onComplete:onComplete};
if (_queues["lower"][0] != i + 1 || _queues["upper"][0] != i + 1) {
var divert:Number = 0;
for (var connection in _connections) {
trace("target: "+_connections[connection].target+" || i: "+(i+1));
if(int(_connections[connection].target) != (i + 1)) {
trace("bad connection");
divert++;
}
}
if (divert == _connections.length) {
_diversion = i + 1;
trace("divert: "+divert+" || connections: "+_connections.length);
}
}
}
First of all, why use a for(var) loop when you can use
var divert:Number = 0;
for each(var connection in _connections) {
trace("target: " + connection.target + " || i: " + (i + 1));
if(int(connection.target) != (i + 1)) {
trace("bad connection");
divert++;
}
}
To debug further, replace
trace("target: " + connection.target + " || i: " + (i + 1));
with
trace("target: " + int(connection.target) + " || i: " + (i + 1));
If this traces zero, you know where the issue is.
You could try doing
if(connection.target.toString() != (i + 1).toString()) {