0

A short description :

01) I dynamically load data from a JSON url into an HTML table. The script is in the external .js file called in the header of the HTML file.

02) I filter the results using a filter at the top of the page for the third column (MAIN VALUE). The script worked fine when I had static data. It stopped working ever since I started pullimg the table data dynamically from a JSON url.

And the JS script is here :

        //It loads the data from the JSON file 
    $.getJSON(
         'http://apolosiskos.co.uk/TEB/MOCK_DATA.json',
         function(data){
             var tr;
    //It loads data from the JSON file to the table
             $.each (data, function (key, val) {
                tr = $('<tr/>');
                tr.append('<td class="name" rel="' + val.first_name + '">' + val.first_name + '</td>');
                tr.append('<td >' + 'TEST' + '</td>');
                tr.append('<td class="metric2" >' + val.id + '</td>');
                tr.append('<td class="metric3"><span class="multTotal">' +'0.00'+ '</span></td>');
            tr.append('<td class="metric3-100"><span class="metric3-100">' +'0.00'+ '</span></td>');
            tr.append('<td class="metric1-100"><span class="metric1-100">' +'0.00'+ '</span></td>');
                $('table').append(tr);
             });
            $("input").keyup(minmax);
            //I even tried the below but did not work
            $('body').on('input', '#counter-low, #counter-high', minmax);
           });

    //The filter function for the MIN MAX values in the MAIN VALUE column
    function minmax() {
        var table = $('table').DataTable();
        $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
            return parseFloat(data[2]) >= parseFloat($('#counter-low').val() || data[2]) 
                && parseFloat(data[2]) <= parseFloat($('#counter-high').val() || data[2])
        });
        $('#counter-low, #counter-high').on('keyup', table.draw);
    }

UPD: I paste the code here that works after an answer below :

$(function(){

//It loads the data from the JSON file 
$.getJSON(
     'http://apolosiskos.co.uk/TEB/MOCK_DATA.json',
     function(data){
         var tr;
//It loads data from the JSON file to the table
         $.each (data, function (key, val) {
            tr = $('<tr/>');
            tr.append('<td class="name" rel="' + val.first_name + '">' + val.first_name + '</td>');
            tr.append('<td ><input class="metric1"/>' + '</td>');
            tr.append('<td class="metric2" >' + val.id + '</td>');
            tr.append('<td class="metric3"><span class="multTotal">' +'0.00'+ '</span></td>');
        tr.append('<td class="metric3-100"><span class="metric3-100">' +'0.00'+ '</span></td>');
        tr.append('<td class="metric1-100"><span class="metric1-100">' +'0.00'+ '</span></td>');
            $('table').append(tr);
         });
//It loads dimension1 from the JSON file to the filter
         $.each (data, function (key, val) {
            li = $('<li/>');
            li.append('<input rel="name" type="checkbox" value="' + val.first_name + '"><label for="cb1">' + val.first_name + '</label></li>');
            $('ul').append(li);
         });
       $('.counter').keyup(minmax);
       $('body').on('input click', 'input:checkbox', filters);
       });

});

//Multiplication of the cells function
function multInputs() {
    var mult = 0;
    $("tr").each(function () {
        var $val1 = $('.metric1', this).val();
        var $val2 = $('.metric2', this).text();
        var $total = ($val1 * 1) * $val2 - $val1;
        $('.multTotal', this).text($total.toPrecision(3));

        var $val3 = $('.multTotal', this).text();
        var $total2 = $val3 / 100
        $('.metric3-100',this).text($total2.toPrecision(3));

        var $total3 = $val1 / 100
        $('.metric1-100',this).text($total3.toPrecision(2));

        mult += $total;
    });
}

//Filter function for the Dimension1 values
function filters() {
    var showAll = true;
    $('tr').not('.first').hide();
    $('input[type=checkbox]').each(function () {
        if ($(this)[0].checked) {
            showAll = false;
            var dimension1= $(this).attr('rel');
            var value = $(this).val();            
            $('td.' + dimension1+ '[rel="' + value + '"]').parent('tr').show();
        }
    });
    if(showAll){
        $('tr').show();
    }
}

//The filter function for the MIN MAX values in the MAIN VALUE column
    function minmax() {
        var table = $('table').DataTable();
        $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
            return parseFloat(data[2]) >= parseFloat($('#counter-low').val() || data[2]) 
                && parseFloat(data[2]) <= parseFloat($('#counter-high').val() || data[2])
        });
        $('#counter-low, #counter-high').on('keyup', table.draw);
    }

1 Answer 1

2

So, answering here, I have downloaded your html, json and js. And then I had 3 changes.

  1. I put everything inside the $(function(){});to JS execute everything just after the entire DOM is loaded.
  2. Add a class in both of min and max input like:

    <input id="counter-min" class="counter"/>

    <input id="counter-max" class="counter"/>

and in js set up to $('.counter').keyup( minmax ); having this minmax as a function you already created;

  1. I put the table html like this one:

    <table> <thead> <tr id="ProductID" class="first"> <th>NAME</th> <th>INPUT</th> <th>MAIN VALUE</th> <th>DIFF</th> <th>DIFF /100</th> <th>MV /100</th> </tr> </thead> <tbody> </tbody> </table>

So, that's have worked for me, I don't know if is

EDIT, for the second time I do it here, I just have commented your getJson to add the data directly on your table and then, I did what I said before:

1 - use the $(function() { .. });

2 - add classes on the counter-high and counter-low, just to attach the event to them and then attached the event with $('.className').keyup( minmax ); and

3 - add the thead and tbody elements in the table

//It loads the data from the JSON file 
$(function() {
  
    var data = [{"id":2.2,"first_name":"Debra","last_name":"Rodriguez","email":"[email protected]","gender":"Female","ip_address":"90.22.159.108"},
{"id":2,"first_name":"Julie","last_name":"Lynch","email":"[email protected]","gender":"Female","ip_address":"54.182.62.180"},
{"id":3,"first_name":"Norma","last_name":"Washington","email":"[email protected]","gender":"Female","ip_address":"70.163.106.64"},
{"id":4,"first_name":"Bobby","last_name":"Castillo","email":"[email protected]","gender":"Male","ip_address":"91.202.59.171"},
{"id":5,"first_name":"Henry","last_name":"Chavez","email":"[email protected]","gender":"Male","ip_address":"32.237.37.185"},
{"id":6,"first_name":"Debra","last_name":"Howard","email":"[email protected]","gender":"Female","ip_address":"17.217.42.49"},
{"id":7,"first_name":"Jason","last_name":"Powell","email":"[email protected]","gender":"Male","ip_address":"14.81.195.117"},
{"id":8,"first_name":"Sean","last_name":"Burns","email":"[email protected]","gender":"Male","ip_address":"213.164.85.212"},
{"id":9,"first_name":"Jacqueline","last_name":"Gordon","email":"[email protected]","gender":"Female","ip_address":"18.251.62.55"},
{"id":10,"first_name":"Russell","last_name":"Richards","email":"[email protected]","gender":"Male","ip_address":"27.226.59.80"},
{"id":11,"first_name":"Albert","last_name":"Perkins","email":"[email protected]","gender":"Male","ip_address":"243.122.251.248"},
{"id":12,"first_name":"Michael","last_name":"Willis","email":"[email protected]","gender":"Male","ip_address":"252.197.211.230"},
{"id":13,"first_name":"Joan","last_name":"Hamilton","email":"[email protected]","gender":"Female","ip_address":"204.70.110.117"},
{"id":14,"first_name":"Eric","last_name":"Garcia","email":"[email protected]","gender":"Male","ip_address":"178.221.216.3"},
{"id":15,"first_name":"Frank","last_name":"Olson","email":"[email protected]","gender":"Male","ip_address":"245.25.170.33"},
{"id":16,"first_name":"Kelly","last_name":"Fuller","email":"[email protected]","gender":"Female","ip_address":"199.209.173.51"},
{"id":17,"first_name":"Frank","last_name":"Cook","email":"[email protected]","gender":"Male","ip_address":"58.30.243.1"},
{"id":18,"first_name":"Alan","last_name":"Rice","email":"[email protected]","gender":"Male","ip_address":"44.231.199.117"},
{"id":19,"first_name":"Mark","last_name":"Greene","email":"[email protected]","gender":"Male","ip_address":"45.34.44.2"},
{"id":20,"first_name":"Charles","last_name":"King","email":"[email protected]","gender":"Male","ip_address":"237.30.205.186"}];
  
    //$.getJSON(
        //'http://apolosiskos.co.uk/TEB/MOCK_DATA.json',
        //function(data) {
            var tr;
            //It loads data from the JSON file to the table
            $.each(data, function(key, val) {
                tr = $('<tr/>');
                tr.append('<td class="name" rel="' + val.first_name + '">' + val.first_name + '</td>');
                tr.append('<td >' + 'TEST' + '</td>');
                tr.append('<td class="metric2" >' + val.id + '</td>');
                tr.append('<td class="metric3"><span class="multTotal">' + '0.00' + '</span></td>');
                tr.append('<td class="metric3-100"><span class="metric3-100">' + '0.00' + '</span></td>');
                tr.append('<td class="metric1-100"><span class="metric1-100">' + '0.00' + '</span></td>');
                $('table').append(tr);
            });
			
            $('body').on('click', 'input[type=checkbox]', minmax);
            $('.counter').keyup(minmax);
            $('input').keyup(multInputs);
            $('body').on('click', '#btnFilter', filtermin);
        });
//});


//The filter function for the first column (NAME)
//This have to work together of the minmax function
function filters() {
	
	//if anyone is checked, return true to show all
	var checkboxChecked = $('input[type=checkbox]:checked');
	if (checkboxChecked.length <= 0) {
		$('tr').show();
		return true;
	}
	
	$('tr').not('.first').hide();
	//else, find the name checked and verify with the name passed as parameter
	
    checkboxChecked.each(function() {
		var dimension1 = $(this).attr('rel');
		var value = $(this).val();
		
		$('td.' + dimension1 + '[rel="' + value + '"]').parent('tr').show();
    });
}

//Multiplication of the cells function
function multInputs() {
    var mult = 0;
    $("tr").each(function() {
        var $val1 = $('.metric1', this).val();
        var $val2 = $('.metric2', this).text();
        var $total = ($val1 * 1) * $val2 - $val1;
        $('.multTotal', this).text($total.toPrecision(3));

        var $val3 = $('.multTotal', this).text();
        var $total2 = $val3 / 100
        $('.metric3-100', this).text($total2.toPrecision(3));

        var $total3 = $val1 / 100
        $('.metric1-100', this).text($total3.toPrecision(2));

        mult += $total;
    });
}

//The filter function for the MIN MAX values in the MAIN VALUE column
function minmax() {
	
	filters();
    $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
        return parseFloat(data[2]) >= parseFloat($('#counter-low').val() || data[2]) &&
            parseFloat(data[2]) <= parseFloat($('#counter-high').val() || data[2]);
    });
	
	var table = $('table').DataTable();
    $('#counter-low, #counter-high').on('keyup', table.draw);
}

function filtermin() {
    var value = $('#filter').val();

    $('tr').show();

    $('tr td.odds').each(function() {
        if ($(this).text() < value) {
            $(this).parent().hide();
        }
    });

}
<head>
    <meta charset="utf-8">
    <meta http-equiv="Access-Control-Allow-Origin" content="*" />
    <title>json extract in datorama tables</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" language="javascript" src="teste.js"></script>
    <link rel="stylesheet" href="css/main.css"/>
    <style href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css"></style>
</head>

<body>
    <h1>discrepancy checker after extracting data in JSON</h1>
    <hr/>
    <div class="row">
        <div class="col-sm-4 filter-columns">
            <div class="ac-custom ac-checkbox ac-cross" autocomplete="off">
                <h2>Dimension1</h2>
                <ul>
                    <li><input rel="name" type="checkbox" value="Debra" id="cb1"><label for="cb1">Debra</label></li>
                    <li><input rel="name" type="checkbox" value="Julie" id="cb2"><label for="cb2">Julie</label></li>
                    <li><input rel="name" type="checkbox" value="Norma" id="cb3"><label for="cb3">Norma</label></li>
                    <li><input rel="name" type="checkbox" value="Bobby" id="cb4"><label for="cb4">Bobby</label></li>
                    <li><input rel="name" type="checkbox" value="Henry" id="cb5"><label for="cb5">Henry</label></li>
                </ul>
            </div>
        </div>
        <div class="col-sm-4 filter-columns-alt">
            <div class="ac-custom ac-checkbox ac-cross" autocomplete="off">
                <h2>MIN MAX</h2>
                Min:<input id="counter-low"  class="counter" type="text" /> &nbsp; 
				Max:<input id="counter-high" class="counter" type="text" />
            </div>
        </div>
        <div class="col-sm-4 filter-columns-alt">
            <input type='text' id='filter' /> <button id='btnFilter'>Go</button>
        </div>
    </div>

    <div id="body">


        <table>
            <thead>
                <tr id="ProductID" class="first">
                    <th>NAME</th>
                    <th>INPUT</th>
                    <th>MAIN VALUE</th>
                    <th>DIFF</th>
                    <th>DIFF /100</th>
                    <th>MV /100</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>

</body>

Sign up to request clarification or add additional context in comments.

14 Comments

I did not get the step 1 to be honest. I have never unified functions in JS.
the step 1: put all your js code into $(function(){ ... put your code here... }); just your functions filters and minmax doesn't need.. this $(function(){ ... }); is the same of $(document).ready(function() { ... }); which means, that all your js, will execute just after the document stay ready, you know? so, all your DOM elements will be created and then your js will execute, that way, you prevent some errors.
It seems to be working but there is an implication between the filters and minmax function. If you type min 15, then choose Debra and then change the min to 5, the filters do not work.
I updated the link if that helps. Replace the test2.html with jsontest.html
you cold load all normally, and after load the data, you call the functions to filter
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.