Javascript

Update parent after children new windows closed

14 Apr , 2015  

Here is a snippet to update parent after new window getting closed :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Start trigger pop-up new window
var createUrl = $(this).data('url') + selectedUUID;
newwindow = window.open(createUrl, 'Some Page, 'scrollbars=yes,resizable=yes,height=600,width='+screen.width/2);

// Set focus on windows
if (window.focus) {
    newwindow.focus();
}

// Update parent once children window already closed
// Reload jqgrid table to get latest data
var monitor = setInterval(function() {
    if (newwindow.closed) {
         // Update children table
         $selectorFarmfield.setGridParam({url: 'someurl' + selectedUUID});
         $selectorFarmfield.trigger("reloadGrid");
         clearInterval(monitor);
    }
}, 1000);

Javascript

Example Jquery Plugin to filtering input value real-time with Regex validation

3 Apr , 2015  

We try to add real-time input validation for dynamic element with some regex. Let say, user allowed only to type “numeric” and disallow any others alphabet and symbols.

Then, we can write a small plugin, at this example, i use https://github.com/akzhan/jquery-keyfilter for Regex validation.

Then, we just need to write this simple and easy plugin :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
(function($) {
    $.fn.validNumber = function(selector) {

        /**
         * Attach key filter with regex int only for dynamic element
         */
        $(document).on('click', selector, function() {
            $(this).keyfilter(/[\dA-F]/);
        });

        /**
         * When input have more than 1 digit but leading with 0
         * Remove the leading zero
         */
        $(document).on('keyup', selector, function() {
            if($(this).val().length > 1 && $(this).val()[0] == "0") {
                 $(this).val($(this).val().substring(1));
            }
        });
    };
})(jQuery);

Then, we just need to use this libraries by :

1
$(document).validNumber('input');

Javascript

Jqgrid for Dummies

1 Apr , 2015  

Here is a quick snippet of how to using JqGrid for dummies, like get data, delete data, access data or data manipulation.

Setup JQGrid:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
$(document).ready(function() {
    // Enable tooltips
$("body").tooltip({
    selector : '[data-toggle="tooltip"]'
});
$(".chosen").chosen();

var permission = $('.permission');

// Define ID for table
var selector = "#table-index";
var pager = '#table-pager';

// Setup url ajax for loading data in table
var url = $(selector).data('url');

// Define last sel for edit
var lastSel;

var colModel =  [
     {name:'id', hidden: true, key:true, editable:true},
     {name:'uuid', hidden: true},
     {name:'hybrid', label:'Hybrid', editable: true, editrules:{number: true}, classes: 'numberonly'},
     {name:'some_date', label:'Date Selection', editable: true,  editoptions:{size:20,
          dataInit:function(el){
                $(el).datepicker({dateFormat:'dd-mm-yy'});
          },
          defaultValue: function(){
            var currentTime = new Date();
            var month = parseInt(currentTime.getMonth() + 1);
            month = month < = 9 ? "0"+month : month;
            var day = currentTime.getDate();
            day = day <= 9 ? "0"+day : day;
            var year = currentTime.getFullYear();
            return day+"-"+month + "-"+year;
          }
        }
      },
 ];

/**
 * Setup Table GRID
 *
 * We need to define colModel with editable and edittype
 * Check to load pager and bind keys
 */
var tableGrid = $(selector).jqGrid({
    url : url,
    datatype : "json",
    colModel : colModel,
    rowNum : 100,
    rowList : [100, 500, 1000],
    pager : pager,
    sortname : 'id',
    sortorder : "desc",
    height: 300,
    jsonReader : {
        repeatitems: false,
        id: "0"
    },
    editurl: $(selector).data('edit-url'),
    viewrecords: true,
    multiselect: true,
    onSelectRow: function(id){
         if(id && id!==lastSel){
            $(selector).restoreRow(lastSel);
            lastSel=id;
         }
   },
});

More…

Javascript

JqGrid save inline editing callback

1 Apr , 2015  

Here is a quick snippet for callback when saving inline editing in JqGrid:

1
2
3
4
5
6
7
8
9
10
11
12
// http://stackoverflow.com/questions/13303698/total-of-amount-in-jqgrid
ondblClickRow: function (rowid, name, val, iRow, iCol) {
    $(selector).jqGrid("editRow", rowid, {
        keys: true,
        aftersavefunc: function (rowid) {
            var $grid = $(selector);
            var colSum = $grid.jqGrid('getCol', 'debit', false, 'sum');
            $grid.jqGrid('footerData', 'set', { 'debit': colSum });
           
        }
    });
},

In this example, we do calculation after inline edit save.

Django,Javascript

JqGrid delete multiple select rows

1 Apr , 2015  

There is an issue if we delete rows using :

1
2
3
4
5
6
7
8
9
10
// Get all selected row
var rows = $(selector).jqGrid("getGridParam", "selarrrow");
console.log(rows);

// Iterate and delete
for (var i in rows) {
      console.log(i);
      console.log(rows[i]);
      $(selector).jqGrid('delRowData', rows[i]);
}

Only a few records will deleted.

The solution :

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * Delete data button handler
 * There is a bug if we delete by forloop, solution
 * http://www.trirand.com/blog/?page_id=393/bugs/delrowdata-bug-on-grid-with-multiselect
 */
$("a.delete-data").click(function(e) {
    e.preventDefault();

    var rowids = $(selector).jqGrid('getGridParam', 'selarrrow');
    for (var i = rowids.length - 1; i >= 0; i--) {
        $(selector).jqGrid('delRowData', rowids[i]);
    }
});

Javascript

Solve issue Fullcalendar count two day as one day

9 Mar , 2015  

This is not bug. When we try to add day in March with start 10-03-2015T10:00:00 and end 11-03-2015T02:00:00, then it will showing one day instead of two day.

To solve this issue, we need to put nextDayThreshold:

1
nextDayThreshold: "00:00"

To make the next day threshold every 00:00

Javascript

Example make reusable javascript app for modal progress bootstrap

26 Feb , 2015  

This is example build reusable app in Javascript for modal progress in Boostrap:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
 * Re-usable app for modal box progress
 */
var progressBox;
progressBox = progressBox || (function() {
    var pleaseWaitDiv =  $('<div class="modal hide" id="pleaseWaitDialog" data-backdrop="static" data-keyboard="false"><div class="modal-header"><h1>Processing...</h1></div><div class="modal-body"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div></div>');
    return {
        showPleaseWait: function() {
            pleaseWaitDiv.modal();
        },
        hidePleaseWait: function() {
            pleaseWaitDiv.modal('hide');
        },
    };
})();

To use, we just need to :

1
progressBox.showPleaseWait();

Javascript

How to hide search toolbar in Datatables

25 Feb , 2015  

Here is a quick snippet to hide search toolbar in datatables and working along with Bootstrap

1
2
3
4
var settings = {
            sDom: 'lrt<"col-sm-6"i><"col-sm-6"p>',
            serverSide : true,
...

Javascript

Set bootstrap datetimepicker input value date

25 Feb , 2015  

Here is a quick way to set value bootstrap datetimepicker input with date object:

1
2
3
4
5
6
$("#id_start_date, #id_end_date").datetimepicker({
    format: "DD-MM-YYYY hh:mm"
});

$('#id_start_date').data("DateTimePicker").setDate(start);
$('#id_end_date').data("DateTimePicker").setDate(end);

Javascript

Datatables make link in row records

20 Feb , 2015  

Here is a quick snippet to make record as links in Datatables :

1
2
3
4
5
6
7
8
columns : [
              {
                "mRender": function ( data, type, full ) {
                 // 'full' is the row's data object, and 'data' is this column's data
                 // e.g. 'full[0]' is the comic id, and 'data' is the comic title
                 return '<a href="' + full['uuid'] + '">' + full['created_by']+ '</a>';
               }
];

Javascript

Jquery Datatables modify fnserverData and pagination

28 Jan , 2015  

Here is a quick snippet for custom AJAX data for Jquery datatables :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 var table = $('#table-index').dataTable({
                "serverSide": true,
                "searching": false,
                "ordering": false,
                "sAjaxSource": url,
                "bStateSave": true,
                "fnStateSave": function (oSettings, oData) {
                    localStorage.setItem( 'DataTables', JSON.stringify(oData) );
                },
                "fnStateLoad": function (oSettings) {
                    return JSON.parse( localStorage.getItem('DataTables') );
                },
                "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
                 oSettings.jqXHR = $.ajax( {
                   "url": sSource,
                   "data": {'page': Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1},
                   "success": fnCallback,
                   "error": function (e) {
                       console.log(e.message);
                   }
                 });
               },
                "columns": [
                    { "data": "name" },
                    { "data": "gender" },
                    { "data": "location" },
                    { data: null,
                      className: "center",
                      defaultContent: '<a href="#" class="edit_data"><i class="fa fa-pencil"></i> Edit</a> |  <a href="" class="remove_data"><i class="fa fa-trash"></i> Remove</a>'
                    }
                ],
            });

For pagination, the key is :

1
 "data": {'page': Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1},

Javascript

Jquery Icheck checkbox checked or not

17 Nov , 2014  

Here is snippet to check if checkbox is checked or not in Jquery iCheck:

1
2
3
4
5
$('input[name="some-input-name"]').on('ifToggled', function (event) {
           if ($(this).is(':checked')) {
               alert('checked');
            }
        });

Javascript

The right way to use setTimeout in inifite loop Javascript

10 May , 2014  

When we using setTimeout, actually it will assigned into some parameters with ID of task. To avoid memory leaks, we should comes with this strategy. First, declare global variable.

1
var timeOutClose;

Let say we have infinite loop function contains :

1
2
3
4
// Run timer to close box
timeOutClose = setTimeout(function() {
    $(".md-close").trigger("click");
}, animationClose * 1000);

Then we make sure to clear timeOutClose variable by put this before execution :

1
2
3
4
5
6
7
8
9
// Clear timeout                   
if (timeOutClose) {
   clearTimeout(timeOutClose);
}

// Run timer to close box
timeOutClose = setTimeout(function() {
    $(".md-close").trigger("click");
}, animationClose * 1000);

Javascript

Beware with jquery animate in infinite loop Javascript caused memory leaks

10 May , 2014  

After do Check memory leak javascript in Chrome, i found that animate and delay in Javascript quite consume memory. And it’s end up with memory leaks.

Here are my code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
for (var i = 0; i < split; i++) {
    ...

    $("tr.cmp_tr").css({
        'display' : 'none'
    });

    for (var k = 0; k < split; k++) {
        TimeOutObj = setTimeout(function() {
            $("tr#cmp" + k).css('opacity', 1).animate({
                opacity : 1
            }, 1000);
        }, 100 * i);
    }

    var k = 0;
    TimeOutObjSecond = setTimeout(function() {
        k += 1;
    }, 100 * i);
}

Then i change this line :

1
2
3
4
5
for (var k = 0; k < split; k++) {
    TimeOutObj = setTimeout(function() {
        $("tr#cmp" + k).show();
    }, 100 * i);
}

Voila! Now memory still in 2.9MB 😀

Javascript

How to insert javascript code into WordPress from plugin using shortcode

4 Jan , 2012  

When we need to inserting Javascript blocks code programmatically into post, we know that WordPress autoescaping Javascript before write into tables. To make javascript inserting into post in WordPress, we can use shortcode. This feature meaning we define custom tag blocks in post and how to convert it tag. So, the tricks is we should define our javascript in shortcode and all needed content leave on block tags. It seem little confuse without any example right?

For instance, I want to inserting Scribd Javascript into WordPress post :
More…

,

Javascript

Solving no docs found for member gjslint on VIM Syntastic

21 Sep , 2011  

Closure Linter (gjslint) is pretty powerfull for checking our javascript code. If you using VIM, then you should consider using Syntastic plugin which is incredibly.

By default, Syntastic will detecting Gjslint, Jslint, JSHint and Javascriptlint in our system. Every editing and saving a JS file, syntastic will do several javascript checker.

Today, i found “no docs found for member” error which it comes from Closure Linter. This is happen because i don’t create JSDoc Annotation in my code. JSDoc is useful for auto-complete on several IDE. But, sometimes people don’t need it.
More…

,

Javascript

Modify Jquery Typing disable enter key / some key from start event

28 Aug , 2011  

I have chat applications based on NodeJS that using Jquery-typing for detecting user activity. This plugin is great, but i facing some problem with enter keys.

I make some script if user press “ENTER”, it will send message. But seems Jquery-typing detect “ENTER” key as start typing activity. It will make my chat application give stop typing notification into another users which message already send. I want to disable some keys in Jquery Typing.

So, i fork from original github and add-ed some additional feature called “keyClear”. Here are some implementation. “ENTER” keyCode is 13. So, i add it into keyclear options :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$('#text-input').typing({
    start: function (event, $elem) {
        if(checkVariable(now.name, now.roomId)){
            now.statusOnWriting();
        }
    },
    stop: function (event, $elem) {
        if(checkVariable(now.name, now.roomId)){
            now.statusOffWriting();
        }
    },
    keyclear: 13,
    delay: 1000
});

Now when people press “ENTER” it make not activity, not start or stop typing either.

You can clone it on : https://github.com/yodiaditya/jquery-typing.

,

Javascript

How to get select value using Jquery

6 Aug , 2011  

Simple things, we want to grab value from select button on Jquery. If you want to get option value of select list, use this :

1
$('select :selected').val();

If you want to get text value in select list, use this :

1
$('select :selected').text();

,

Javascript

Auto remember form input content while typing using JQUERY

6 Aug , 2011  

When clients inserting data into form, suddenly their connection lost or accidentally refreshed the web page. And guess what? they facing new empty form again and feel tired to inserting same data again. We can reduce this by using JQUERY cookies which can remember what clients type into form. So, when they refreshed pages even close and open it again, they have previous input data.

To do this, you must download Jquery & Jquery Cookies.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<script type="text/javascript">

    function remember( selector ){
        $(selector).each(
                function(){
                    //if this item has been cookied, restore it
                    var name = $(this).attr('name');
                    if( $.cookie( name ) ){
                        $(this).val( $.cookie(name) );
                    }
                    //assign a change function to the item to cookie it
                    $(this).change(
                    function(){
                        $.cookie(name, $(this).val(), { path: '/', expires: 1 });
                    }
                );
            }
        );
    }

    $(document).ready(function(){

       $(function() {
            remember('[name=website]');
        })

        $('#region a').click(function(){
            var newValue = $('#OodleSearch').val() + ' ' +$(this).text();
            $('#OodleSearch').attr('value',newValue);
        })

    })
</script>

Now if you have input form with name attribute is “website” :

1
<input type="text" name="website" />

Then, now it’s auto remembering.

Kudos to : http://www.komodomedia.com/blog/2008/07/using-jquery-to-save-form-details/

,