Sorting datatables with IP-Adresses and hyperlinks - javascript

My datatable was acting cool and all until I modified integer element of a particular column(with hyperlinks) to IP Adresses. All of a sudden the sorting feature was acting weird.
Before I had something like this :
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script type="text/javascript" src="includes/js/jquery.js"></script>
<script type="text/javascript" src="includes/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8">
jQuery.fn.dataTableExt.oSort['intComparer-asc'] = function (a, b) {
var m = a.match(/^\<.*\>(\d+)\<.*\>/);
a = m[1];
var m = b.match(/^\<.*\>(\d+)\<.*\>/);
b = m[1];
var value1 = parseInt(a);
var value2 = parseInt(b);
return ((value1 < value2) ? -1 : ((value1 > value2) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['intComparer-desc'] = function (a, b) {
var m = a.match(/^\<.*\>(\d+)\<.*\>/);
a = m[1];
var m = b.match(/^\<.*\>(\d+)\<.*\>/);
b = m[1];
var value1 = parseInt(a);
var value2 = parseInt(b);
return ((value1 < value2) ? 1 : ((value1 > value2) ? -1 : 0));
};
$(document).ready(function() {
$('#tableAsI').dataTable({
'aoColumnDefs': [
{ 'sType': 'intComparer', 'aTargets': [ 0, 1 ] }
]
});
});
</script>
<table class="table" id="tableAsI">
<thead> <tr class="infoo"> <th>N</th> <th>IP</th> </tr> </thead>
<tbody>
<?php
echo '<tr><td>2</td>';
echo '<td >13</td>';
echo'</tr>';
echo '<tr> <td>4</td>';
echo '<td >1</td>';
echo'</tr>';
echo '<tr><td>1</td>';
echo '<td >2</td>';
echo'</tr>';
echo '<tr><td>3</td>';
echo '<td >20</td>';
echo'</tr>';
?>
</tbody>
</table>
And the sorting works well, but after adding the IP Adresses i have this for example:
<td >100.130.6.109</td>
and the result is :
100.130.6.109
**100.130.6.11**
100.130.6.110
100.130.6.111
What i want is this :
**100.130.6.11**
100.130.6.109
100.130.6.110
100.130.6.111
Thanks.

How about using this plugin (or the code from it in the case of extra links support)? https://datatables.net/plug-ins/sorting/ip-address
The plugin uses the code like this:
var m = a.split("."), x = "";
But, because you also have the hyperlink, with a small help of jQuery, you can easily parse and extract the content of the link. For example:
$('100.130.6.109').html();
This will give you 100.130.6.109 exactly. Thus, the small modification to the plugin code would look like this:
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"ip-address-pre": function(a) {
var ip_address = $(a).html();
var m = ip_address.split("."), x = "";
...

Related

How to trigger onChange event when form is submitted?

I'm trying to populate HTML table with filter(two dropdowns) from CSV file by using PHP, JS, and jQuery. When user open the page user will see below dropdown,
the options for this drop downs are file names in the dir.
<form name="form1" method="post">
<select class="form-control col-sm-5" onChange="document.forms['form1'].submit();" id="choosefile" name="choosefile">
<option value="" selected>Choose Term</option>
<?php
foreach ($files as &$value) {
echo '<option value="' . $value . '">' . $value . '</option>';
}
?>
</select>
</form>
when user submit the form below PHP code gets executed
<?php
if(isset($_POST['choosefile']) && !empty($_POST['choosefile'])) {
$t = $_POST["choosefile"];
$filepath = "uploads/$t";
$row = 0;
$the_big_array = [];
$unique_start_date = [];
$unique_ids = array();
if (($h = fopen("{$filepath}", "r")) !== false) {
while (($data = fgetcsv($h, 1000, ",")) !== false) {
$the_big_array[] = $data;
$unique_ids[] = $data[0];
$a unique_start_date[] = $data[1];
}
fclose($h);
}
//closing bracket for parent if statement is at the end of the file
?>
Below two dropdowns act as a filter
<select name="" id="session_id">
<option value="">[Select Session]</option>
</select>
<select name="" id="start_date">
<option value="">[Select Start Date]</option>
</select>
<table border="1" class="table" id="personDataTable">
<thead>
<tr>
<th scope="col">Session</th>
<th scope="col">Start Date</th>
</tr>
</thead>
<tbody id='tbody'>
</tbody>
</table>
<script>
var obj1 = <?php array_shift($the_big_array); echo json_encode($the_big_array); ?>;
var obj2 = <?php array_shift($unique_start_date); echo json_encode(array_unique($unique_start_date)); ?>;
var obj3 = <?php array_shift($unique_ids); echo json_encode(array_unique($unique_ids)); ?>;
var table = document.getElementById("personDataTable").getElementsByTagName("tbody")[0];
var temp,temp1 = {};
var row = 0;
$("#choosefile, #session_id, #start_date").on('change', function() {
var d1 = $( "#session_id" ).val();
var d2 = $( "#start_date" ).val();
$("#tbody").empty();
for (var i = 0; i < obj1.length; i++) {
if (d1 && obj1[i][0] !== d1 && row > -1) continue;
if (d2 && obj1[i][1] !== d2 && row > -1) continue;
row++;
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][0]));
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][1]));
}
});
</script>
<?php }?>
The problem I'm having is when user submit first dropdown(options with file name) table doesn't get generated or it does not call .on('change', function() under which table generator code is present.
I'm not able to trigger that .on('change', function() for first dropdown but when user click on filter dropdowns that part works well
This answer is an extent to my last comment, as example.
//Put it into a seperate named function:
function fillTable() {
var d1 = $( "#session_id" ).val();
var d2 = $( "#start_date" ).val();
$("#tbody").empty();
for (var i = 0; i < obj1.length; i++) {
if (d1 && obj1[i][0] !== d1 && row > -1) continue;
if (d2 && obj1[i][1] !== d2 && row > -1) continue;
row++;
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][0]));
newTr.insertCell(-1).appendChild(document.createTextNode(obj1[i][1]));
}
}
// reference to that function here
$("#choosefile, #session_id, #start_date").on('change', fillTable);
// call when the page is loading:
fillTable();

Get highest value from <td> in table by class

How can I get the highest value in a table column by class? I have tried the following:
HTML
<table>
<tr><td class="speed">1.1</td></tr>
<tr><td class="speed">3.1</td></tr>
<tr><td class="speed">5.5</td></tr>
<tr><td class="speed">2.0</td></tr>
</table>
jQuery/Javascript
function gethighestspeeds(){
var speeds = $(".speed").map(function() {
return parseFloat(this.text, 10);
}).get();
var highestspeed = Math.max.apply(Math, speeds);
alert(highestspeed)
}
Also, how can I get all values if > than a certain number?
this.text is undefined for the td element, you need to parse parseFloat($(this).text(), 10);
function gethighestspeeds() {
var speeds = $(".speed").map(function() {
return parseFloat($(this).text(), 10);
}).get();
var highestspeed = Math.max.apply(Math, speeds);
snippet.log('high: ' + highestspeed);
var num = 2.3;
var array = $(".speed").map(function() {
var flt = parseFloat($(this).text(), 10);
return flt > num ? flt : undefined;
}).get();
snippet.log('array: ' + array)
//if you already have the speeds array
var array2 = speeds.filter(function(val) {
return num < val;
});
snippet.log('array2: ' + array)
}
gethighestspeeds();
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="speed">1.1</td>
</tr>
<tr>
<td class="speed">3.1</td>
</tr>
<tr>
<td class="speed">5.5</td>
</tr>
<tr>
<td class="speed">2.0</td>
</tr>
</table>
Try this........
var certainNumber=2.2; //Whatever you want to set
function gethighestspeeds(){
var speeds = $(".speed").map(function() {
return parseFloat(this.text, 10) > parseFloat(certainNumber);
}).get();
}
You have to use : $(this).text() instead of this.text in your map function:
return parseFloat($(this).text(), 10);

JQuery tablesorter custom sorter using textExtraction and textSorter

I have a column that have both date and text data:
<td>
<div class="date">07/01/2016</div>
<div class="status">open</div>
</td>
I need to first sort the date, then within the same date, sort by the text of "status" div. Following code is what I have so far using textExtraction and textSorter option, but the column is not sorting. The strange thing I found out is, when I change the first row into:
<td><span class="date">07/31/2016</span><div class="status">open</div></td>
it was able to sort the rest of the table without the first row. Can anyone help? Thanks. jsfiddle link (here)
$(document).ready(function() {
$('#articles-table').tablesorter({
textExtraction:{
2:function(node, table, cellIndex){
var $n = $(node).find('div');
return $.trim($n.eq(0).text())+";"+$.trim($n.eq(1).text());
}
},
textSorter:{
2:function(a, b){
var aArr = a.split(";")[0].split('/');
var bArr = b.split(";")[0].split('/');
var aDate = aArr[2] + aArr[0] + aArr[1] + "";
var bDate = bArr[2] + bArr[0] + bArr[1] + "";
var result= aDate < bDate ? -1 : (aDate > bDate ? 1 : 0);
if (!result) { // Level 1 is equal
var sa = a.split(";")[1];
var sb = b.split(";")[1];
result = sa.localeCompare(sb);
}
return result;
}
}
});
});
EDIT: Solved by adding class="sorter-text" on th to set sorter type as text.

Mysql Table Sorting in Php (Client side)

Can any one help how to sort the database results in php
i have pasted the my code below. it display the result but sorting cannot be done.
Any help in this regard
<script language="JavaScript" type="text/javascript">
<!--
var sortedOn = 0;
function SortTable(sortOn) {
var table = document.getElementById('results');
var tbody = table.getElementsByTagName('tbody')[0];
var rows = tbody.getElementsByTagName('tr');
var rowArray = new Array();
for (var i=0, length=rows.length; i<length; i++) {
rowArray[i] = rows[i].cloneNode(true);
}
if (sortOn == sortedOn) { rowArray.reverse(); }
else {
sortedOn = sortOn;
if (sortedOn == 0) {
rowArray.sort(RowCompareNumbers);
}
else if (sortedOn == 3) {
rowArray.sort(RowCompareDollars);
}
else {
rowArray.sort(RowCompare);
}
}
var newTbody = document.createElement('tbody');
for (var i=0, length=rowArray.length; i<length; i++) {
newTbody.appendChild(rowArray[i]);
}
table.replaceChild(newTbody, tbody);
}
function RowCompare(a, b) {
var aVal = a.getElementsByTagName('td')[sortedOn].firstChild.nodeValue;
var bVal = b.getElementsByTagName('td')[sortedOn].firstChild.nodeValue;
return (aVal == bVal ? 0 : (aVal > bVal ? 1 : -1));
}
function RowCompareNumbers(a, b) {
var aVal = parseInt(a.getElementsByTagName('td')
[sortedOn].firstChild.nodeValue);
var bVal = parseInt(b.getElementsByTagName('td')
[sortedOn].firstChild.nodeValue);
return (aVal - bVal);
}
function RowCompareDollars(a, b) {
var aVal = parseFloat(a.getElementsByTagName('td')
[sortedOn].firstChild.nodeValue.substr(1));
var bVal = parseFloat(b.getElementsByTagName('td')
[sortedOn].firstChild.nodeValue.substr(1));
return (aVal - bVal);
}
//-->
</script>
Php MySql Query
<?php
$job_id = $_GET['id'] ;
$sql="SELECT date, fullname, city, education from table_name
WHERE id = 'job_id'";
$result=mysql_query($sql); ?>
<table id="results" style="width:980px;">
<thead>
<tr>
<th style="width:60px;"><a onclick="SortTable(0);" href="javascript:;">Date</a></th>
<th style="width:150px;"><a onclick="SortTable(1);" href="javascript:;">Name</a></th>
<th style="width:70px;"><a onclick="SortTable(2);" href="javascript:;">City</a></th>
<th style="width:70px;"><a onclick="SortTable(3);"href="javascript:;">Education</a>
</th>
<?php while($rows=mysql_fetch_array($result)){
?>
<tbody>
<tr>
<td>1</td>
<td><? echo $fullname ; ?></td>
<td><? echo $city ; ?></td>
<td><? echo $b_education ; ?></td>
</tr>
</tbody>
<?
}
?>
</table>
$job_id = $_GET['id'] ;
$sql="SELECT date, fullname, city, education from table_name
WHERE id = 'job_id'";
will not work,
first it should id = '" . $job_id . "' (your WHERE condition search for the id "job_id" not the $job_id variable
2nd based on this lines, google the words "sql injection" ... thats a big security issue! (msyql_real_escape for example)
3rd, mysql provides ORDER functions... if you want client side order, build the result, convert it to json (json_encode) and handle it with javascript, but yours is crappy ^^
regards
Thomas

Clone Table Row Not Working

I am having a weird problem. I am creating a metabox for wordpress and came across an issue where a <tr> will not clone on .click. I am using a while php loop and can get div, p, a, etc tags to clone but not luck with the table. Here is a look at the code.
<?php while($mb->have_fields_and_multi('ingredients')) : ?>
<?php $mb->the_group_open(); ?>
<tr>
<td>Blah</td>
</tr>
<?php $mb->the_group_close(); ?>
<?php endwhile; ?>
add row
Here is the javascript
$('[class*=docopy-]').click(function(e)
{
e.preventDefault();
var p = $(this).parents('.postbox'); /*wp*/
var the_name = $(this).attr('class').match(/docopy-([a-zA-Z0-9_-]*)/i)[1];
var the_group = $('.wpa_group-'+ the_name +'.tocopy', p).first();
var the_clone = the_group.clone().removeClass('tocopy last');
var the_props = ['name', 'id', 'for', 'class',];
the_group.find('*').each(function(i, elem)
{
for (var j = 0; j < the_props.length; j++)
{
var the_prop = $(elem).attr(the_props[j]);
if (the_prop)
{
var the_match = the_prop.match(/\[(\d+)\]/i);
if (the_match)
{
the_prop = the_prop.replace(the_match[0],'['+ (+the_match[1]+1) +']');
$(elem).attr(the_props[j], the_prop);
}
the_match = null;
// todo: this may prove to be too broad of a search
the_match = the_prop.match(/n(\d+)/i);
if (the_match)
{
the_prop = the_prop.replace(the_match[0], 'n' + (+the_match[1]+1));
$(elem).attr(the_props[j], the_prop);
}
}
}
});
if ($(this).hasClass('ontop'))
{
$('.wpa_group-'+ the_name, p).first().before(the_clone);
}
else
{
the_group.before(the_clone);
}
checkLoopLimit(the_name);
$.wpalchemy.trigger('wpa_copy', [the_clone]);
});
});
I apologize for the amount of javascript and I couldn't replicate the problem just jsfiddle.

Categories