.every method not matching all elements to IF statement - javascript

I have a function that scans the child elements of a td element in a table for the string "green.png" in the columns declared in the "columns" array. It then passes the result to a function which reorders the table based on the result.
I am using the .every method to ensure that all the child elements in the selected columns contain "green.png" before executing, however it executes when any of the columns contain this value.
My understanding of the .every method is that it will ensures the condition is met for every object in the array before executing, but this is not occurring. Could someone advise what is missing/incorrect with my code?
Here is the code that parses the element:
function checkRowGreen(tenant) {
var columns = ["COLUMN1", "COLUMN2", "COLUMN3", "COLUMN4", "COLUMN5"];
var count = 0;
columns.every(function(column) {
var element = document.getElementById(tenant + column);
if(element != null && element.firstElementChild != null && element.firstElementChild.src.indexOf('green.png') > -1) {
console.log("[INFO] Found successful PNG on " + tenant + " column " + column + " - found " + count);
count++;
}
});
return count > 0;
}
And here is the code that reorders the table:
if(checkRowGreen(tenant)) {
var row = document.getElementById(tenant + "Row");
var table = document.getElementById("tenantTable");
if(row == null || table == null) return true;
var cells = row.getElementsByTagName("td");
table.deleteRow(row.rowIndex);
var newRow = table.insertRow(-1);
newRow.id = rowID;
for(var i = cells.length-1; i >= 0; i--) {
bugout.log("[INFO] inserting cell.." + i + " out of " + cells.length);
var newCell = newRow.insertCell(0);
newCell.innerHTML = cells[i].innerHTML;
newCell.id = cells[i].id;
}
}

Syntax should be something like:
if(myArray.every(myFuncName))
{
...
}
or
var result = myArray.every(myFuncName);
or
var result = mArray.every(element => element.age >= 5);
etc.

Related

REDIPS get results as array from function and pass it to ajax

Im using REDIPS library so i can drag and drop some elements in a table. Following the provided examples by the library, I want to get the save_content() result as an array so I can insert those values inside my DB. This is my approach, but it doesn't work. Right now I get the value in an input displayed as text
save_content = function (tbl) {
var query = '', // define query parameter
tbl_start, // table loop starts from tbl_start parameter
tbl_end, // table loop ends on tbl_end parameter
tbl_rows, // number of table rows
cells, // number of cells in the current row
tbl_cell, // reference to the table cell
t, r, c, d; // variables used in for loops
// first sort tables array to it's original order
tables.sort(function (a, b) {
return a.idx - b.idx;
});
// if input parameter is undefined, then method will return content from all tables
if (tbl === undefined) {
tbl_start = 0;
tbl_end = tables.length - 1;
}
// if input parameter is out of range then method will return content from first table
else if (tbl < 0 || tbl > tables.length - 1) {
tbl_start = tbl_end = 0;
}
// else return content from specified table
else {
tbl_start = tbl_end = tbl;
}
// iterate through tables
for (t = tbl_start; t <= tbl_end; t++) {
// define number of table rows
tbl_rows = tables[t].rows.length;
// iterate through each table row
for (r = 0; r < tbl_rows; r++) {
// set the number of cells in the current row
cells = tables[t].rows[r].cells.length;
// iterate through each table cell
for (c = 0; c < cells; c++) {
// set reference to the table cell
tbl_cell = tables[t].rows[r].cells[c];
// if cells isn't empty (no matter is it allowed or denied table cell)
if (tbl_cell.childNodes.length > 0) {
// cell can contain many DIV elements
for (d = 0; d < tbl_cell.childNodes.length; d++) {
// childNodes should be DIVs, not \n childs
if (tbl_cell.childNodes[d].tagName === 'DIV') { // and yes, it should be uppercase
var value = $(tbl_cell).find("input").val();
query += 'p[]=' + tbl_cell.childNodes[d].id //obj id
+ '_' + value + '_' + r + '_' + c + '&';
}
}
}
}
}
}
// cut last '&'
query = query.substring(0, query.length - 1);
// return prepared parameters (if tables are empty, returned value could be empty too)
return query;
};
I would like to get the query value as an array so i can insert the values into the database without using $_REQUEST
function save() {
$('#moverCita').modal('toggle');
var content = REDIPS.drag.save_content();
document.getElementById("moverCitaRow").value = content;
}
I get the value as text inside the input
update.php
if (isset($_POST['submit'])){
if(isset($_POST['moverCitaRow'])){
if (!empty($_POST['moverCitaRow'])) {
$content = $_POST['moverCitaRow'];
$content = #$_REQUEST['p'];
if(is_array($content)) {
foreach ($content as $c) {
list($job_id, $job_bay_id, $row, $col) = explode('_', $c);
try {
update_calendar($job_id, $job_bay_id, $row, $col);
} catch (Exception $ex) {
$_SESSION["errorMsg"] = $ex->getMessage();
$_SESSION["errorType"] = "danger";
}
}
}
}
else {
echo '<center><strong style="color:red;">Llenar todos los campos
requeridos</strong></center><br>';
}
}
}

How can I sort a data table numerically with jquery

I have a HTML table and the jQuery code to sort the table alphabetically but I can't figure out how to order one of the columns numerically. It is only ordering the numeric column by the first number and not the longer numbers. So 99 shows up at the top and not 9340.
$('thead th').each(function(column) {
$(this).addClass('sortable').click(function(){
var findSortKey = function($cell) {
return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
};
var sortDirection = $(this).is('.sorted-asc') ? -1 : 1;
//step back up the tree and get the rows with data
//for sorting
var $rows = $(this).parent().parent().parent().find('tbody tr').get();
//loop through all the rows and find
$.each($rows, function(index, row) {
row.sortKey = findSortKey($(row).children('td').eq(column));
});
//compare and sort the rows alphabetically
$rows.sort(function(a, b) {
if (a.sortKey < b.sortKey) return -sortDirection;
if (a.sortKey > b.sortKey) return sortDirection;
return 0;
});
//add the rows in the correct order to the bottom of the table
$.each($rows, function(index, row) {
$('tbody').append(row);
row.sortKey = null;
});
//identify the column sort order
$('th').removeClass('sorted-asc sorted-desc');
var $sortHead = $('th').filter(':nth-child(' + (column + 1) + ')');
sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc');
//identify the column to be sorted by
$('td').removeClass('sorted')
.filter(':nth-child(' + (column + 1) + ')')
.addClass('sorted');
});
});
function filterDataTable(selector,query){
query = $.trim(query);
query = query.replace(/ /gi, '|');
$(selector).each(function(){
($(this).text().search(new RegExp(query, "i")) < 0 ) ? $(this).hide().removeClass('visibile') : $(this).show().addClass('visible');
});
}
$('tbody tr').addClass('visible');
$("#filter").keyup(function(event){
if(event.keyCode == 27 || $(this).val() == ''){
$(this).val('');
$('tbody tr').removeClass('visible').show().addClass('visible');
}else {
filter('tbody tr', $(this).val());
}
});
$('#filter').show();
I did some googling to see if a question was asked like this but I couldn't find one to fit what I needed exactly. Most of them told others to use plugins but I don't want to add any plugins. I want to have my own sorting code. Thanks.
You can fill your number with 0 to get a sortable string :
var myNumber = 12;
var filler = "00000000000";
var res = filler.substr(0, filler.length - myNumber.toString().length) + myNumber;
Normally, res = 0000000012
You can have your number back if needed with parseInt(res,10)
This code is working in your snippet.
var findSortKey = function($cell) {
var sk = $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
var ik = parseInt(sk,10);
return ik != NaN ? ik : sk;
};

How can I show only the row of a table that has the same value that was entered in a textbox with jquery

I have a table of rank where I type the ID of the rank and it shows me only the column line that has this line as my code:
$('button').click(function () {
var data = $("textarea").val();
var rank = $("#rank").val();
if(rank == ""){
alert("digit rank number");
}
else{
data = data.replace(/\s/, " #");
data = data.replace(/([0-9]\s)/g, "$1#");
var lines = data.split("#"),
output = [],
i;
for (i = 0; i < lines.length; i++)
output.push("<tr><td>" + lines[i].slice(0,-1).split(",").join("</td><td>") + "</td></tr>");
output = "<table>" + output.join("") + "</table>";
var valuefinal = $(output).find('tr').filter(function(){
return $(this).children('td').eq(1).text() == rank;
});
$('#fileDisplayArea').html(valuefinal);
}
});
I'm doing this filter in that part of the code
var valuefinal = $(output).find('tr').filter(function(){
return $(this).children('td').eq(1).text() == rank;
});
$('#fileDisplayArea').html(valuefinal);
DEMO CODE
(Forgive me if you did not understand something, my english sucks. I hope it is clear what I need.)
You need to change this -
return $(this).children('td').eq(1).text() == rank;
to this -
return $(this).children('td').eq(0).text() == rank;
.eq() is a zero-based array method.
http://jsfiddle.net/jayblanchard/qM6Fj/19/
http://api.jquery.com/eq/
You need to have a search feature for the contents you have displayed in the table is what i got.....
You can use jQuery DataTable for this purpose which does this job link .. scroll down to see the table show with sort, search etc features

Sorting dynamic table in jquery

Sorry but I'm completly new to js and jquery.
I got dynamic table which values are in localstorage. I can add new row, delete row, and edit cells. This is working.
I want to add a sorting this table by clicked colum. I found here code and try it. It just working when I write table and not use my javascript to add rows from localstorage. Table in two cases looks same in html code. I have no idead why sorting isnt working with dynamic table.
This is w/o my dynamic table from localstore, sorting as supposed to:
http://jsfiddle.net/eW8Kg/1/
This is with table from localstorage(not working in jsfiddle?) on my comupter this is working good, but table is not sorting! (I left this static values):
http://jsfiddle.net/XAu5G/
I think my problem can be in creation of table content:
var Html = "<tbody>";
for (var i = 1; i < localStorage.length; i++) {
var input = "<td><input style='border:hidden' class=\"fields\" name = " + localStorage.key(i) + " type='text' onchange='change(\"" + localStorage.key(i) + "\")' /></td>"
Html += "<tr class=\"field\">";
for (var j = 0; j < 4; ++j) {
Html += input;
}
var button = "<td><input type='button' value = 'UsuĊ„' onclick='Remove(\"" + localStorage.key(i) + "\")'></td>";
Html += button + "</tr>";
}
Html += "<tr id=\"actions\"></tr></tbody>"
document.getElementById("list").innerHTML += Html;
This jquery code do sorting:
$(document).ready(function() {
var table = $('#list');
jQuery.fn.sortElements = (function() {
var sort = [].sort;
return function(comparator, getSortable) {
getSortable = getSortable || function() {return this;};
var placements = this.map(function() {
var sortElement = getSortable.call(this),
parentNode = sortElement.parentNode,
// Since the element itself will change position, we have
// to have some way of storing it's original position in
// the DOM. The easiest way is to have a 'flag' node:
nextSibling = parentNode.insertBefore(
document.createTextNode(''),
sortElement.nextSibling
);
return function() {
if (parentNode === this) {
throw new Error(
"You can't sort elements if any one is a descendant of another."
);
}
// Insert before flag:
parentNode.insertBefore(this, nextSibling);
// Remove flag:
parentNode.removeChild(nextSibling);
};
});
return sort.call(this, comparator).each(function(i) {
placements[i].call(getSortable.call(this));
});
};
})();
$('#x').click(function(){
$('#list').hide();
});
$('#nazwa-header').wrapInner('<span title="sort this column"/>').each(function() {
var th = $(this),
thIndex = th.index(),
inverse = false;
th.on('click', function() {
table.find('td').filter(function() {
return $(this).index() === thIndex;
}).sortElements(function(a, b) {
console.log($(a).find('input').val(),$(b).find('input').val());
return $(a).find('input').val() > $(b).find('input').val() ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}, function() {
// parentNode is the element we want to move
return this.parentNode;
});
inverse = !inverse;
});
});
});

Adding Select All checkbox in a new row after combining two tables

I have successfully implemented select all check box at the end of the row in case there is only one table to display. However in one of the tab I am combining two tables data and dividing them in two columns thus the number of rows are different in those two columns.
I am trying to figure out how to populate two different select all checkbox at the end of the rows in both columns.
I am populating tables dynamically using JS. Here is my code
HTML
<div id="tabs">
<ul id="betTypesTabs"></ul>
</div>
JS for populating the table data from two sources
function drawSelectionsForDoubles(table, events, indexes) {
// Array of Horse Selections for every event
var arrayOfSelections = [];
$.each(indexes, function (i, index) {
arrayOfSelections[i] = events[index].markets[0].selections;
});
// Max number of Selections
var maxNumberOfSelections = 0;
for (var i=0; i<arrayOfSelections.length; i++) {
if (arrayOfSelections[i].length > maxNumberOfSelections) maxNumberOfSelections = arrayOfSelections[i].length;
}
// Going through all the selections in the horizontal manner
for (var i=0; i<maxNumberOfSelections; i++) {
for (var j=0; j<arrayOfSelections.length; j++) {
var currentHorse = arrayOfSelections[j][i];
// If the horse exists
if (currentHorse != null) {
// If the horse is participating in Running Double bet
$.each(currentHorse.prices, function(index, value) {
if (value.betTypeId == 108) {
// Adding the record
// First tds in the row
if (j == 0) {
var tr = createTr(table.id + '_' + i, "white");
$(tr).append(createTd(null, null, currentHorse.position, null));
$(tr).append(createTd(null, null, currentHorse.name, null));
var td = createTd(null, null, "",null);
td.appendChild(createInput(table.id + '_' + i + "_doubles_" + currentHorse.id, table.id + "_doubles_1", "checkbox", null));
$(tr).append(td);
$(table).append(tr);
}
// Second column
else {
tr = document.getElementById(table.id + '_' + i);
if (tr == null) {
var tr = createTr(table.id + '_' + i, "white");
$(table).append(tr);
var td = createTd(null, null, '', 3);
$(tr).append(td);
}
$(tr).append(createTd(null, null, currentHorse.position, null));
$(tr).append(createTd(null, null, currentHorse.name, null));
var td = createTd(null, null, "",null);
td.appendChild(createInput(table.id + '_' + i + "_doubles_" + currentHorse.id, table.id + "_doubles_2", "checkbox", null));
$(tr).append(td);
}
}
});
}
}
}
}
Now since the rows in two columns are different I want to add an extra row after the table where I can add a checkbox which will select all the rows in the table.

Categories

Resources