The checkbox in the header has the id which is combined from the “cb_” prefix and the grid id. So you can hide the element with

var myGrid = $("#list");
$("#cb_"+myGrid[0].id).hide();

There is a separate event handler to capture the Select All event. From the documentation:

onSelectAll

Sends you the following parameters: aRowids, status

This event fires when multiselect option is true and you click on the header checkbox. aRowids is an array of the selected rows (rowid’s). status is a boolean variable determining the status of the header check box – true if checked, false if not checked. Note that the aRowids array will always contain the ids whether the header checkbox is checked or unchecked.

When this event fires, in your case you’ll want to do the following to show the correct count of selected rows:

onSelectAll: function(aRowids, status) {
    //Use a ternary operator to choose zero if the header has just been unchecked, or the total items if it has just been checked.
    $("totalSelected").val(status === false ? 0 : aRowids.length);
}

Posting Values to CFC using JQUERY

Posted: January 11, 2016 in JQuery

Using $.POST method we can achieve this. Below is the syntax.

$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});

For Example,

jQuery(“#BTN_REMOV”).click( function() {
var s;
CurrentPubNum=”12344″;
DBName=”testdb”;
DBUserType=”testdbtype”;
DBUserName=”testuser”;
DBUserPass=”TestPass”;
s = jQuery(“#list1”).jqGrid(‘getGridParam’,’selarrrow’); //for getting the list of all selected rowids from jqgrid
res=s;
res=res.join();
$.post(“RelatedPublication.cfc”,                      {method:”RemovePublicationsFromRelatedGrid”,PublicationID:res,CurrPub:CurrentPubNum,DBName:DBName,DBType:DBUserType,DBUser:DBUserName,DBPass:DBUserPass, returnFormat:”json”},
function(IsSuccess) {
if(IsSuccess == 1){
alert(“Publication removed successfully.”);

}
else
{
alert($.trim(IsSuccess));
}
})

});

In case you don’t have CF10, this is my preferred way to remove duplicates from a list.

<cfset newlist = [] />
<cfloop list=”#combination#” index=”i”>
<cfif NOT arrayFind(newlist,trim(i))> // can also use arrayFindNoCase
<cfset arrayAppend(newlist,trim(i))>
</cfif>
</cfloop>

<cfoutput>
#arraytolist(newlist)#
</cfoutput>

Use the below function to properly formatting decimal numbers.

var value = format_number(newnumber,2);

For example, if you want to convert 0.575 into 0.58, you can use the below function to achieve it.

var value = format_number(0.575,2);

function format_number(pnumber,decimals){
if (isNaN(pnumber)) { return 0};
if (pnumber==”) { return 0};

var snum = new String(pnumber);
var sec = snum.split(‘.’);
var whole = parseFloat(sec[0]);
var result = ”;

if(sec.length > 1){
var dec = new String(sec[1]);
dec = String(parseFloat(sec[1])/Math.pow(10,(dec.length – decimals)));
dec = String(whole + Math.round(parseFloat(dec))/Math.pow(10,decimals));
var dot = dec.indexOf(‘.’);
if(dot == -1){
dec += ‘.’;
dot = dec.indexOf(‘.’);
}
while(dec.length <= dot + decimals) { dec += ‘0’; }
result = dec;
} else{
var dot;
var dec = new String(whole);
dec += ‘.’;
dot = dec.indexOf(‘.’);
while(dec.length <= dot + decimals) { dec += ‘0’; }
result = dec;
}
return result;
}

Use REReplace

#reReplace(testString,”\s+”,” “,”All”)#

This a regular expression replace.
The first param is the string that the extra white space is to be stripped
from.
The second param is a regular expression which you are looking to replace.
The regular expression “\s+” means one or more white space characters.
The third param is the string that you will be putting in place of the
previous.
The fourth param is optional, “All” indicates that you would like to replace
all instances of the reg expression. The default for this param is “One” which
will replace only the first occurance.

The code below will allow you to see it in action.
<cfset testString = “my cold fusion server”>
<pre>
#testString#
#reReplace(testString,”\s+”,” “,”All”)#
</pre>


We can display a clock which will be showing the local time of the client computer by using JavaScript. Note that this time displayed is taken from user computer and not from the server.

We have seen in our date object example how to display current date and time where the current date and time is displayed once. Here we will try to display changing clock or real time change in date and time by using setTimeout function. This setTimeout function we have used to trigger the time display function in a refresh rate of 1000 mill seconds ( 1 Sec ). This refresh rate can be changed to any other value. By changing the value to 5000 the clock will refresh and show the exact time once in every 5 seconds.

 

Here is the code

<html>
<head>
<title>(Type a title for your page here)</title>
<script type="text/javascript"> 
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}

function display_ct() {
var strcount
var x = new Date()
document.getElementById('ct').innerHTML = x;
tt=display_c();
 }
</script>
</head>

<body onload=display_ct();>
<span id='ct' ></span>

</body>
</html>

Changing the display format

To change the display format we need to change the function part only where we can change the display part.
Let us start with using UTC String.

function display_ct() {
var strcount
var x = new Date()
var x1=x.toUTCString();// changing the display to UTC string
document.getElementById('ct').innerHTML = x1;
tt=display_c();
 }

The output is here
Wed, 29 Oct 2014 14:17:28 GMT

Displaying in mm/dd/yy H:m:s format

Here is the code

function display_ct() {
var strcount
var x = new Date()
var x1=x.getMonth() + "/" + x.getDate() + "/" + x.getYear(); 
x1 = x1 + " - " +  x.getHours( )+ ":" +  x.getMinutes() + ":" +  x.getSeconds();
document.getElementById('ct').innerHTML = x1;

tt=display_c();
 }

Note that we have only changed the display_ct() function part , other code remains same. Here is the output 9/29/114 – 19:47:28

To display clock inside a textbox

Create a textbox and give id to it

<input type=text id='t1' size='70'>

For displaying add this line inside the function display_ct()

document.getElementById('t1').value = x;

 

We can show a count down script displaying time left from an event. Say we are running a campaign which is going to end after two days. Here we will display a counter saying days , hours , minutes and seconds left for the event to happen or the campaign to end. This script uses the setTimeout function in the same way as it is used in displaying a changing clock script. Here this setTimeout script triggers another function in every 1000 mill seconds ( or in 1 sec ).

This script uses client side JavaScript to generate the count down clock. The initial value in number of seconds left for the countdown to end will be passed to the function. At the time of page loading the seconds left ( a numeric value ) is collected and based on this value the days , hours, minutes and seconds are calculated and displayed. So this script can be run by linking to a server side script like PHP or ASP and a powerful dynamic script can be developed. Let us not discuss the server side script part and we will only run the script with some numeric value for seconds which is collected at the time of page loads.

The script uses two functions. While the page loads we use the onload event of the body tag  and pass a value to the function display_c().

<body onload=display_c(86501);>

Now this value of 86501 ( in Seconds ) is used to calculate the number of days, hours , minutes and seconds left for the event to happen.

Since this value we are going to use it again and again so we kept this in a global variable to use it inside and outside the functions like this

window.start = parseFloat(start);

WE have used windows object to store a variable in global scope to use throughout the page.

Now in each successive call to the function the value of this window.start is decreased by one after displaying the countdown value. The count down value changes after ever second and it gets the value after a short calculation.

window.start= window.start- 1;

The days left is calculated by taking the Math.floor value after dividing total time by 86400. This value of 86400 is the total number of seconds in a day ( 60 second x 60 minutes x 24 hours )

Similar way values of hours , minutes and seconds are calculated. A detail help is kept with comment lines inside the code.

Finally using a span id the count down is displayed.

71743 Seconds or (0 Days 19 Hours 55 Minutes and 43 Secondes )

Here is the code

<!doctype html public “-//w3c//dtd html 3.2//en”>

<html>
<head>
<title>(Type a title for your page here)</title>
<script type=”text/javascript”>
function display_c(start){
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh=1000; // Refresh rate in milli seconds
if(window.start >= end ){
mytime=setTimeout(‘display_ct()’,refresh)
}
else {alert(“Time Over “);}
}

function display_ct() {
// Calculate the number of days left
var days=Math.floor(window.start / 86400);
// After deducting the days calculate the number of hours left
var hours = Math.floor((window.start – (days * 86400 ))/3600)
// After days and hours , how many minutes are left
var minutes = Math.floor((window.start – (days * 86400 ) – (hours *3600 ))/60)
// Finally how many seconds left after removing days, hours and minutes.
var secs = Math.floor((window.start – (days * 86400 ) – (hours *3600 ) – (minutes*60)))

var x = window.start + “(” + days + ” Days ” + hours + ” Hours ” + minutes + ” Minutes and ” + secs + ” Secondes ” + “)”;

document.getElementById(‘ct’).innerHTML = x;
window.start= window.start- 1;

tt=display_c(window.start);
}
</script>
</head>

<body onload=display_c(86501);>
<span id=’ct’ style=”background-color: #FFFF00″></span>

</body>
</html>

<cfinput type=”checkBox” id=”Del_check” name=”Del_check” value=”#avgGrade_history_id_pk#”>

var selpos = $(“input[name=’Del_check’]:checked”).val();
if (!selpos)
{
alert(“Please select history item to be deleted!!”);
return false;
}

Suppose you have a list of items arranged in a table and you want to change the order of the items -Jquery UI has a wonderful and easy to use plugin for this – know as Sortable. The sortable plugin allows us to do the sorting using drag and drop with mouse click. In this article we will see the sortable plugin in action using drag and drop and also using separate UP / DOWN buttons.

Consider the following html markup for our sample table:

HTML Page
<table class="table table-striped">
    <tbody id="tabledivbody">
        <tr class="sectionsid" id="sectionsid_1">
                <td>Overview</td>
                <td><a href="javascript:void(0)" class="movedownlink">
                     <span class="glyphicon glyphicon-arrow-down"></span></a></td>
                <td></td>
        </tr>
        <tr class="sectionsid" id="sectionsid_2">
                <td>History behind OOPS</td>
                <td><a href="javascript:void(0)" class="movedownlink" >
                     <span class="glyphicon glyphicon-arrow-down"></span></a></td>
                <td><a href="javascript:void(0)" class="moveuplink" >
                     <span class="glyphicon glyphicon-arrow-up"></span></a></td>
                <td></td>
        </tr>
        <tr class="sectionsid" id="sectionsid_3">
                <td>Summary</td>
                <td><a href="javascript:void(0)" class="moveuplink" >
                     <span class="glyphicon glyphicon-arrow-up"></span></a></td>
                <td></td>
        </tr>
    </tbody>
</table>

CFM Page

Use the ajaxonload() function to trigger the sortable function.
Syntax : <cfset ajaxonload('FunctionName')>

example: <cfset ajaxonload('dragTableRow')>

This markup when rendered looks like this –

Now, as you can see that there are 3 items in the table and if needed we can rearrange and change their order using the up / down arrow keys or simply dragging one row and placing over another row. It may look fancy and tough, but it is actually very easy to achieve the same. Just read on…

Step 1: Include the following jquery scripts for Sortable to work:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>

 

Step 2: Following javascript code is required to make the table rows sortable:

Option 1

function dragTableRow(){
$(“#Tableid tbody”).sortable({
helper: fixHelperModified ,opacity: 0.6, cursor: ‘move’, update: function() {
var order = $(this).sortable(“serialize”) + ‘&action=updateRecordsListings’;
$.post(“cfm page”, order, function(theResponse){
//alert(theResponse)

});
}
});
}

Option 2

    $("#tabledivbody").sortable({
        items: "tr",
        cursor: 'move',
        opacity: 0.6,
        update: function() {
            sendOrderToServer();
        }
    });
   
    function sendOrderToServer() {
        var order = $("#tabledivbody").sortable("serialize");
   
        $.ajax({
        type: "POST", dataType: "json", url: "/path/to/updateorder/script",
        data: order,
        success: function(response) {
            if (response.status == "success") {
                window.location.href = window.location.href;
            } else {
                alert('Some error occurred');
            }
        }
        });
    }


To make the rows sortable, you need to use table body (tbody) as the selector. Sortable plugin also provides a way to let us know the current order of the rows. For this, the sortable plugin expects us to provide them some info in the form of id attributes of the rows. See – id=”sectionsid_1″ in our html example. Once you get this step correct, you can get the current order of items in a serialized array using – $(“#tabledivbody”).sortable(“serialize”) statement. This ordering information can also be passed on to the server to be updated in a Database too. Here in this example we are using an AJAX call to our backend so that as soon as the order changes we update the same in our database and once the response has come back from server, we refresh the page to display the recently updated order from the Database. The POST data may look like – sectionsid[]=1&sectionsid[]=2&sectionsid[]=3

Step 3: processing order array at the backend:

The following is an example in php to demonstrate how to handle this ordering information and store it in Database:

PHP Code

        $sectionids = $_POST('sectionsid');
        $count = 1;
        if (is_array($sectionids)) {
            foreach ($sectionids as $sectionid) {
                $query  = "Update sections SET display_order = $count";
                $query .= " WHERE id='".$sectionid."'";
               
                // your DB query here
               
                $count++;
            }
           
            echo '{"status":"success"}';
        } else {
            echo '{"status":"failure", "message":"No Update happened. Could be an internal error, please try again."}';
        }

Coldfusion Code

<cfset s=Form[‘SECTIONSID[]’] >
<cfset listingCounter = 1>
<cfloop list=”#s#” index=”recordIDValue”>
<cfquery name=”Qry_Name” datasource=”DSN”>

Update Table SET  display_order =#listingCounter#

WHERE  id==#recordIDValue#
</cfquery>
<cfset listingCounter=listingCounter+1>
</cfloop>
The above code assumes that you have a column – ‘display_order’ to maintain order for each item in database table.

How to handle separate UP / DOWN arrow keys:

Add the following javascript code to reorder the table rows using individual buttons:

    $(".moveuplink").click(function() {
        $(this).parents(".sectionsid").insertBefore($(this).parents(".sectionsid").prev());
        sendOrderToServer();   
    });
   
    $(".movedownlink").click(function() {
        $(this).parents(".sectionsid").insertAfter($(this).parents(".sectionsid").next());
        sendOrderToServer();
    });

What is happening here, is that as soon as an arrow button is clicked(whether it is up or down identified by their classes – moveuplink and movedownlink respectively) – the rows are dynamically updated in the table DOM hierarchy. And as before, upon clicking of these buttons the information is again sent back to the backend, where the same can be updated in the Database.

That’s all what is needed to get the table rows sorted either by drag and drop or by clicking specific buttons.

PS: While working with this, you might observe a wierd issue while dragging a table row. Sometimes, the width of the row gets collapsed and the row looks shrinked than the actual width. The issue can be fixed(courtsey ) by providing a custom helper callback as follows:

    var fixHelper = function(e, ui) {
        ui.children().each(function() {
            $(this).width($(this).width());
        });
        return ui;
    }
   
    $("#tabledivbody").sortable({
        ------
        helper: fixHelper,
    });