Archive for the ‘JavaScript’ Category

function isValid(str){
return !/[&\[\]\\’/()\\””]/g.test(str);
}

function ValidateSpecialChar()
{
var ErrorMsg = “Special Charectors & [ ] ‘ / ( ) \\ \” are not allowed in”;
var IsValid=1;

var PrenomTxt = $(‘#Prenom’).val();
var NomDeFamilleTXT = $(‘#NomDeFamille’).val();

if(isValid(PrenomTxt) == false)
{
ErrorMsg = ErrorMsg +”\n -First name”;
IsValid =0;

}
if(isValid(NomDeFamilleTXT) == false)
{

ErrorMsg = ErrorMsg +”\n -Last name”;
IsValid =0;
}

if(IsValid ==0)
{
alert(ErrorMsg);
return false;
}
return true;
}

Set URL dynamically for JQgrid

Posted: January 20, 2016 in JavaScript, JQuery

We can use the setGridParam method for setting the URL dynamically. Below is the syntax and example for this.

Syntax:

$(“#gridname”).setGridParam(
{
url:”new url”,
page:1
}
).trigger(“reloadGrid”);//Reload grid trigger

Example:

$(“#list”).setGridParam(
{
url:”RelatedPublication.cfc?method=GetUnrelatedPublications&PublicationID=”+pubid,
page:1
}
).trigger(“reloadGrid”);//Reload grid trigger

The below code works with and without the loadOnce option set to true. Note that you have to set the rowNum option to 0 first, if you leave out this option it’ll still default to the 20 records to show. Also, I’m assuming you’re returning the total rows from the server in the documented JSON reader format.

$(‘#bla’).jqGrid({

  ‘rowNum’      : 0,
‘loadOnce’    : true,
loadComplete:function(){
  $(this).jqGrid(‘setGridParam’, ‘rowNum’, ‘records‘);
},

//The JSON reader. This defines what the JSON data returned from the CFC should look like
jsonReader: {
root: “ROWS”, //our data
page: “PAGE”, //current page
total: “TOTAL”, //total pages
records:”RECORDS”, //total records
userdata:”USERDATA”, //Userdata we will pass back for feedback
cell: “”, //Not Used
id: “0” //Will default to frist column
}

});

 

 

Altrow is not working in JQgrid

Posted: January 13, 2016 in JavaScript, JQuery

There are many methods to set alternate row color for jqgrid.

We can use altRow and altClass property in jqgrid for achieving this. Following is my code:

altRows:true,
altclass:’myAltRowClass’

and CSS is

.myAltRowClass
{
background-color: Fuchsia;
background-image:none;
}

2. By adding a new CSS class to jqgrid.css we can achieve this. Below is the steps to do this

1. Set grid property altRows:true,
2. Add the below CSS class to end of grid.css
.ui-jqgrid tr.ui-priority-secondary td { background-color: #DDDDDD; }

3. Without using altRows and altClass property.

loadComplete: function() {
$(“tr.jqgrow:odd”).css(“background”, “#DDDDDC”);


									

Use the recordtext property wit value like below.

recordtext:'{0} – {1} of {2} records’

For example,

var grid = $(“#list1″)
grid.jqGrid({
url:”RelatedPublication.cfc, //CFC that will return the users
datatype: ‘json’, //We specify that the datatype we will be using will be JSON
colNames:[‘UPID’,’PUBNUMBER’,’VOL”], //Column Names

colModel :[
{name:’UPID’,index:’UPID’, width:50,resizable:false,sortable:true,sorttype:”int”,resizable:false,editrules:{readonly:true}},
{name:’PUBNUMBER’,index:’PUBNUMBER’, width:130,resizable:false, sorttype:”text”,editable:true,edittype:”text”,editoptions:{size:30,maxlength:50},editrules:{required:true}},
{name:’VOL’,index:’VOL’, width:150,resizable:false, align:”left”,sorttype:”text”,editable:true,edittype:”text”,editoptions:{size:30,maxlength:50},editrules:{required:true}},
],

pager: $(‘#pager1’), //The div we have specified, tells jqGrid where to put the pager
rowNum:25, //Number of records we want to show per page
rowList:[25,50,100,500,1000,5000,10000,15000,20000,50000], //Row List, to allow user to select how many rows they want to see per page
sortorder: “asc”, //Default sort order
sortname: “ID”, //Default sort column
viewrecords: true, //Shows the nice message on the pager
imgpath: ‘/themes/jqgrid/css/images’, //Image path for prev/next etc images
caption: ‘Related Publications’, //Grid Name
mtype:’GET’,
recordtext:'{0} – {1} of {2} records’,
scrollerbar:true

 

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);
}

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;
}

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>