Monday 29 October 2012

Print Area


How to print selected area



you want to print selected area from the full web page you need to implement this code, you can easy to solve your problem.
exp:
 










In the above example you can print only displaying table using below code.

Add code in your .js file.
<script type="text/javascript">

function print1(strid)
{
if(confirm("Do you want to print?"))
{
var values = document.getElementById(strid);
var printing =
window.open('','','left=0,top=0,width=550,height=400,toolbar=0,scrollbars=0,sta­?tus=0');
printing.document.write(values.innerHTML);
printing.document.close();
printing.focus();
printing.print();
printing.close();
}
}
</script>

HTML code.

<div id="print2">
<table width="40%" cellpadding='0' cellspacing='0' border="1">
    <tr bgColor="#ccc">
        <th>Sno</th><th>Name</th><th>Address</th>
    </tr>
    <tr>
        <td>1</td><td>sonu</td><td>6355</td>
    </tr>
    <tr>
        <td>2</td><td>ankush</td><td>hno 3322</td>
    </tr>
    <tr>
        <td>3</td><td>dimple</td><td>hno 1245</td>
    </tr>
    <tr>
        <td>4</td><td>reena</td><td>3344</td>
    </tr>
    <tr>
        <td>5</td><td>sonu</td><td>6355</td>
    </tr>
    <tr>
        <td>6</td><td>ankush</td><td>hno 3322</td>
    </tr>
    <tr>
        <td>7</td><td>dimple</td><td>hno 1245</td>
    </tr>
    <tr>
        <td>8</td><td>reena</td><td>3344</td>
    </tr>
</table>
</div>
<br/><br/>
<input type="button"  name="printbutton" value="Prin table" onclick="return print1('print2')"/>


You can implement above script in your project you just need to give id for div and pass from the print function.


You can try this example.


SnoNameAddress
1sonu6355
2ankushhno 3322
3dimplehno 1245
4reena3344
5sonu6355
6ankushhno 3322
7dimplehno 1245
8reena3344


Thursday 25 October 2012

Full screen popup

You want to add popup in your site, it is very easy to implement popup in your site just use given code.

<div class="overlay" id="over-flow">   
</div>
<div class="main-box" id="compare-box">
    <span class="close-btn" onclick="boxClose()">Close</span>
</div>

Add CSS in your css file.
<style>
       .overlay{
             display:none;
              z-index:4;
             position:fixed;
             background:#000;
              opacity:0.8;
            left:0;
                top:0;
             right:0;
           bottom:0;
        }
     .main-box{
          display:none;
                left:10px; top:10px; right:10px; bottom:10px;
               background:#FDFFF4;
                  z-index:100;
                      color:#000;
                    position:absolute;
                     border:2px solid #ddd;
                 padding:5px;
    }
    .close-btn{
              padding:5px 10px 5px 10px;
                              border-radius:5px;
                         cursor:pointer;
                        background:#ccc;
                           float:right;
                     font-family:verdana;
                 font-size:12px;
      }
</style>

Add this script in your .js file.
<script>
        function boxClose(){
        $('#over-flow').hide();
        $('#compare-box').hide();
    }
    function get_compare(){
        $('#over-flow').show();
        $('#compare-box').show();
    }
</script>


Try this example:

 
Close

Tuesday 7 August 2012

Check Uncheck List

Script for Check and Uncheck list of check box. just click on header check box all check box automatically checked.

<form action="" method="post" name="frmBrand">
<input type="checkbox" id="master" onClick="check_unChack_All(frmBrand)">

<input type="checkbox" name="brand_id" id="brand_id" value="123">
<input type="checkbox" name="brand_id" id="brand_id" value="123">
<input type="checkbox" name="brand_id" id="brand_id" value="123">

</form>

<script>

function check_unChack_All(field){
var act=true;
if(document.getElementById('master').checked==true){
act=true;
}else{ act=false;}
for (i = 0; i < field.length; i++){
field[i].checked = act ;
}
}
</script>


Saturday 4 August 2012

Common Validation Function

Common validation function which used during the project.


you can create common.js file and save these below function and keep in your project it will help to validate your url, email validate, contact number, string, numeric etc.


function getObject(val){
return document.getElementById(val);
}


function trim(b)
{
var i=0;
while(b.charAt(i)==" ")
{
i++;
}
b=b.substring(i,b.length);
len=b.length-1;
while(b.charAt(len)==" ")
{
len--;
}
b=b.substring(0,len+1);
return b;
}

function checkAtLeastOneBox(name) {

count = 0;
elements = document.getElementsByName(name);
len = elements.length;
for (var i = 0; i < len; i++) {
var e = elements[i];
if (e.checked) {
count=count+1;
}
}

if(count == 0){
return false;
} else {
return true;
}
}


function isCharsInBag (s, bag){
var i;
for (i = 0; i < s.length; i++)
{
var c = s.charAt(i);
if (bag.indexOf(c) == -1) return false;
}
return true;
}

function isZIP(s){
return isAlphaNumeric(s);
}


function isValidUrlAddress(strUrl) {
 
  var v = new RegExp();
v.compile("[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
if (!v.test(strUrl)) {
return false;
}
return true;
}



function checkURL(value) {

var urlregex = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
if(urlregex.test(value))
{
return(true);
}
return(false);
}

function isValidUrl(strUrl) {
  var v = new RegExp();
v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
if (!v.test(strUrl)) {
return false;
}
return true;
}

function isValidUrl2(strUrl) {
  var v = new RegExp();
v.compile("^[A-Za-z0-9-_:\/]+\\.[A-Za-z0-9-_%&\?\/.=]+\\.[A-Za-z]+$");
if (!v.test(strUrl)) {
return false;
}
return true;
}
function isChar(s){
s=trim(s);
return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ");
}


function isName(s){
s=trim(s);
return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ- ");
}
function isName(s){
s=trim(s);
return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ- ");
}
function isPassword(s)
{

s=trim(s);
return isCharsInBag (s, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_");
}

//function to check valid Telephone,. Fax no. etc
function isPhone(s)
{
return isCharsInBag (s, "0123456789-+(). ");//simple test
var PNum = new String(s);
// 555-555-5555
// (555)555-5555
// (555) 555-5555
// 555-5555
// NOTE: COMBINE THE FOLLOWING FOUR LINES ONTO ONE LINE.
var regex = /^[0-9]{3,3}\-[0-9]{3,3}\-[0-9]{4,4}$|^\([0-9]{3,3}\) [0-9]{3,3}\-[0-9]{4,4}$|^\([0-9]{3,3}\)[0-9]{3,3}\-[0-9]{4,4}$|^[0-9]{3,3}\-[0-9]{4,4}$/;

//var regex = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/; //(999) 999-9999 or (999)999-9999
if( regex.test(PNum))
return true;
else
return false;
}

function isAlphaNumeric(s){
return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789- ");
}

function isUserName(s){
s=trim(s);
return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.");
}

function isEmpty(s)
{
s=trim(s);
return ((s == null) || (s.length == 0));
}

//function to check valid email id
function isEmail(s)
{
var regex = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i
var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return regex.test(s);
}


function isInteger (s){
var i;
if (isEmpty(s))
if (isInteger.arguments.length == 1) return 0;
 else return (isInteger.arguments[1] == true);
for (i = 0; i < s.length; i++) {
var c = s.charAt(i);

if (!isDigit(c)) return false;
}

return true;
}

function isDigit (c){
 return ((c >= "0") && (c <= "9"))
}


function setFocus(el){
if(el != "undefined"){
document.getElementById(el).focus();
setAlertStyle(el);
// addEvent(document.getElementById(el),'onblur',function(){ alert('hello!'); })
}else if(typeof gl_el != "undefined"){
gl_el.focus();
}
return true;

}
 

function setAlertStyle(el){
document.getElementById(el).style.border = '2px solid';
document.getElementById(el).style.borderColor = '000';
}
 
function unsetAlertStyle(el){
document.getElementById(el).style.border = '2px solid';
document.getElementById(el).style.borderColor = '#f0f0f1';
}

function SetAllCheckBoxes(FormName,FieldName){
var isChecked=document.getElementById('checkAll').checked;

if(isChecked==true){
var CheckValue='true';

}
else
{
var CheckValue='';
}

if(!FormName)
return;
var objCheckBoxes = document.forms[FormName].elements[FieldName];

if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;

if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
{
objCheckBoxes[i].checked = CheckValue;


}
}

function isAllcheckBoxSelected(formObj,checkBoxName){
var status = false;
var countCheckBoxes = 0;
var objCheckBoxes = formObj.elements[checkBoxName];
countCheckBoxes = objCheckBoxes.length;
if(countCheckBoxes!=0){
for(var i = 0; i <countCheckBoxes; i++){
if(objCheckBoxes[i].checked==true){
status = true;
}else{
status = false;
break;
}
}
}if(!countCheckBoxes) {
if(objCheckBoxes.checked==true){
status = true;
}else {
status = false;
}
}
return status;
}


function checkMasterCheckBox(checkBoxObj,formName,checkBoxName,masterCheckBoxName){
allCheckBoxCheckedStatus = false;
formObj = getObject(formName);
masterCheckBoxObj = getObject(masterCheckBoxName);
allCheckBoxCheckedStatus = isAllcheckBoxSelected(formObj,checkBoxName);
//alert(allCheckBoxCheckedStatus);
if(checkBoxObj.checked==true){
if(allCheckBoxCheckedStatus==true){
masterCheckBoxObj.checked = true;
}
}else{
masterCheckBoxObj.checked = false;
}

}


function showchkbox(){
$(document).ready(function(){
$('#chkTab').toggle('slow');
$('#downarrow').toggle('slow');
});
}

/**
* shows a popup<br />
* depends on jquery<br />
* there should be empty div named winhidelayer on page.<br />
* @param id of popup div
*/
function showPopup(id){
var height = $(window).height();
var winwidth = $(window).width();

try{

$('#winhidelayer').show();
 $('#winhidelayer').css({
'left' : 0,
'top' :0,
'height' : height,
'width' : winwidth

});
}catch(error){
}
$('#'+id).show();
var snpopup = $('#'+id);
var width = $(document).width();

snpopup.css({
'left' : width/2 - (snpopup.width() / 2),
'top' : height/2 - (snpopup.height() / 2),
'z-index' : 1000000                      
});
}

/**
* hide a popup<br />
* depends on jquery<br />
* there should be empty div named winhidelayer on page.<br />
* @param id of popup div
*/
function hidePopup(id){
try{
$('#winhidelayer').hide();
}catch(error){
}
$('#'+id).hide();
}


function daysInMonth(iMonth,iYear)
{


var days=32 - new Date(iYear, iMonth, 32).getDate();

return days;

}


function validateZipCode(elementValue){
 var zipCodePattern = /^\d{5}$|^\d{5}-\d{4}$/;
 return zipCodePattern.test(elementValue);
}

function allValid(s){
s=trim(s);
return isCharsInBag (s, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz. ");
}

function priceValid(s){
s=trim(s);
return isCharsInBag (s, "0123456789. ");
}


Above function used for validation.

Validate Function in javascript


Accept only required value.
Suppose you are using text box for contact number and you want that text box only accept numeric value other values don't allow and name text box only accept alphabetical so you can use given function.

you need to add jquery.js file in your code.

User Name           <input type="text" name="username" id="username">
Contact Number  <input type="text" name="cnumber" id="contactNumber"> 
DOB                     <input type="text" name="userDate" id="userDate"> 

you just need set your controller id,

<script type="text/javascript">
//---------------------------------Only accept numerical value for contact number-----------------------//
$(document).ready(function() {
    $("#contactNumber").keydown(function(event) {
        // Allow: backspace, delete, tab and escape
        if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || 
             // Allow: Ctrl+A
            (event.keyCode == 65 && event.ctrlKey === true) || 
             // Allow: home, end, left, right
            (event.keyCode >= 35 && event.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        else {
            // Ensure that it is a number and stop the keypress
            if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                event.preventDefault(); 
            }   
        }
    });
});
//---------------------------------Only accept numerical value for Area code-------------------------------//
$(document).ready(function() {
    $("#areaCode").keydown(function(event) {
        // Allow: backspace, delete, tab and escape
        if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || 
             // Allow: Ctrl+A
            (event.keyCode == 65 && event.ctrlKey === true) || 
             // Allow: home, end, left, right
            (event.keyCode >= 35 && event.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        else {
            // Ensure that it is a number and stop the keypress
            if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                event.preventDefault(); 
            }   
        }
    });
});
/*--------------------------------only accept date of birth---------------------------------*/
$(document).ready(function() {
    $("#userDate").keydown(function(event) {
        // Allow: backspace, delete, tab and escape
        if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode==111 || event.keyCode == 27 || 
             // Allow: Ctrl+A
            (event.keyCode == 65 && event.ctrlKey === true) || 
             // Allow: home, end, left, right
            (event.keyCode >= 35 && event.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        else {
            // Ensure that it is a number and stop the keypress
            if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                event.preventDefault(); 
            }   
        }
    });
});
//---------------------------------Only accept alfabatical value for name code-------------------------------//
$(document).ready(function() {
    $("#username").keydown(function(event) {
        // Allow: backspace, delete, tab and escape
        if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || 
             // Allow: Ctrl+A
            (event.keyCode == 65 && event.ctrlKey === true) || 
             // Allow: home, end, left, right
            (event.keyCode >= 35 && event.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        else {
            // Ensure that it is a number and stop the keypress
            if ((event.keyCode < 65 || event.keyCode > 90)) {
                event.preventDefault(); 
            }   
        }
    });
});
 </script>

add this script in your js file.

Friday 3 August 2012

Date Difference

Date Difference between two dates.
you can find difference between two date according to interval 
interval can be:
yyyy - Number of full years
q - Number of full quarters
m - Number of full months
y - Difference between day numbers
(eg 1st Jan 2004 is "1", the first day. 2nd Feb 2004 is "33". The datediff is "-32".)
d - Number of full days
w - Number of full weekdays
ww - Number of full weeks
h - Number of full hours
n - Number of full minutes
s - Number of full seconds (default)


function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {
if (!$using_timestamps) {
$datefrom = strtotime($datefrom, 0);
$dateto = strtotime($dateto, 0);
}
$difference = $dateto - $datefrom; // Difference in seconds
switch($interval) {
case 'yyyy': // Number of full years
$years_difference = floor($difference / 31536000);
if (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom), date("j", $datefrom), date("Y", $datefrom)+$years_difference) > $dateto) {
$years_difference--;
}
if (mktime(date("H", $dateto), date("i", $dateto), date("s", $dateto), date("n", $dateto), date("j", $dateto), date("Y", $dateto)-($years_difference+1)) > $datefrom) {
$years_difference++;
}
//$years_difference++;
$datediff = $years_difference;
break;
case "q": // Number of full quarters
$quarters_difference = floor($difference / 8035200);
while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($quarters_difference*3), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
$months_difference++;
}
$quarters_difference--;
$datediff = $quarters_difference;
break;
case "m": // Number of full months
$months_difference = floor($difference / 2678400);
while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($months_difference), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
$months_difference++;
}
$months_difference--;
$datediff = $months_difference;
break;
case 'y': // Difference between day numbers
$datediff = date("z", $dateto) - date("z", $datefrom);
break;
case "d": // Number of full days
$datediff = floor($difference / 86400);
break;
case "w": // Number of full weekdays
$days_difference = floor($difference / 86400);
$weeks_difference = floor($days_difference / 7); // Complete weeks
$first_day = date("w", $datefrom);
$days_remainder = floor($days_difference % 7);
$odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?
if ($odd_days > 7) { // Sunday
$days_remainder--;
}
if ($odd_days > 6) { // Saturday
$days_remainder--;
}
$datediff = ($weeks_difference * 5) + $days_remainder;
break;
case "ww": // Number of full weeks
$datediff = floor($difference / 604800);
break;
case "h": // Number of full hours
$datediff = floor($difference / 3600);
break;
case "n": // Number of full minutes
$datediff = floor($difference / 60);
break;
default: // Number of full seconds (default)
$datediff = $difference;
break;
}
return $datediff;
}




Random Code Generate

Random Code Generate Function:
This function use to generate a random number group of alpha numeric, you just need to pass size of code it will return alpha numeric random number.
For example you pass 10 number it will return 10 digit alpha numeric random number.


function generateRefCode($num) {

$charsAlpha = "abcdefghijklmnopqrstuvwxyz";
srand((double)microtime()*1000000);
$i = 0;
$passAlpha = '' ;

while ($i < $num/4) {
$num = rand() % 33;
$tmp = substr($charsAlpha, $num, 1);
$passAlpha = $passAlpha . $tmp;
$i++;
}

$charsNum = "0123456789";
srand((double)microtime()*1000000);
$i = 0;
$passNum = '' ;

while ($i < $num) {
$num = rand() % 33;
$tmp = substr($charsNum, $num, 1);
$passNum = $passNum . $tmp;
$i++;
}
$strReturn = $passAlpha."-".$passNum;
return $strReturn;
}