Facebook

Monday, December 5, 2011

How do I count the number of tr elements within a table using jquery.


This can be a most basic question, but it may keep us busy us for hours wasting our time.

Use a selector that will select all the rows and take the length.
var rowCount = $('#myTable tr').length;

Note: this approach also counts all trs of every nested table!
$('#myTable tr').size() will return the same value
the docs indicate that length is preferred over size() because it's faster

Sunday, December 4, 2011

Javascript IsInteger


A simple and javascript function to check whether the string is an integer.

function isInteger(s){
var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))){
return false;
}
    }
    // All characters are numbers.
    return true;
}

Saturday, December 3, 2011

How to change PHP's eregi to preg_match



This function eregi has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Now what we need is to replace the eregi functions used in our old applications with some new functions that are still not depreciated...
First i will describe functionality of eregi() and then i will go for appropriate function to replace it.

eregi():
eregi — Case insensitive regular expression match
Syntax:

int eregi ( string $pattern , string $string [, array &$regs ] )

This function is identical to ereg() except that it ignores case distinction when matching alphabetic characters.


Parameters






pattern
Case insensitive regular expression.
string
The input string.
regs
If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs.
$regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched.


return Values

Returns the length of the matched string if a match for pattern was found in string, or FALSE if no matches were found or an error occurred.
If the optional parameter regs was not passed or the length of the matched string is 0, this function returns 1.

A good alternative is to use preg_match() function

Now lets talk about preg_match

preg_match — Perform a regular expression match

Description

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int$offset = 0 ]]] )
Searches subject for a match to the regular expression given in pattern.

More details can be found at php.net http://in2.php.net/manual/en/function.preg-match.php

Now How to replace eregi with preg_match


You will need to change three things
  1. need to add pattern delimiters (can be any character, but most commonly a forward slash)
  2. [[:alnum:]] will need to be replaced with the PCRE equivalent
  3. The "i" in "eregi" means case-insensitive, which PCRE does with a flag, specifically the i flag.
Otherwise, the rest looks PCRE compatible (yes, that's kind of redundant =P)
"/^[a-z0-9][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i"


Thursday, December 1, 2011

How to change version of php in Xampp


Take this example that makes PHP version from 5.3 to 5.2 in Xampp


  1. Download and install latest xampp to G:\xampp. As of 2010/03/12, this is 1.7.3.
  2. Download the zip of xampp-win32-1.7.0.zip, which is the latest xampp distro without php 5.3. Extract somewhere, e.g. G:\xampp-win32-1.7.0\
  3. Remove directory G:\xampp\php
  4. Remove G:\xampp\apache\modules\php5apache2_2.dll and php5apache2_2_filter.dll
  5. Copy G:\xampp-win32-1.7.0\xampp\php to G:\xampp\php.
  6. Copy G:\xampp-win32-1.7.0\xampp\apache\bin\php* to G:\xampp\apache\bin
  7. Edit G:\xampp\apache\conf\extra\httpd-xampp.conf.
    • Immediately after the line, <IfModule alias_module> add the lines
(snip)
<IfModule mime_module>
  LoadModule php5_module "/xampp/apache/bin/php5apache2_2.dll"
  AddType application/x-httpd-php-source .phps
  AddType application/x-httpd-php .php .php5 .php4 .php3 .phtml .phpt
    <Directory "/xampp/htdocs/xampp">
      <IfModule php5_module>
        <Files "status.php">
            php_admin_flag safe_mode off
        </Files>
      </IfModule>
    </Directory>
</IfModule>
(Note that this is taken from the same file in the 1.7.0 xampp distribution. If you run into trouble, check that conf file and make the new one match it.)
You should then be able to start the apache server with PHP 5.2.8. You can tail the G:\xampp\apache\logs\error.log file to see whether there are any errors on startup. If not, you should be able to see the XAMPP splash screen when you navigate to localhost.

Thursday, September 1, 2011

Codeigniter Callback Function to validate date.


function validdate($str){
    if ( ereg("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $str) ) {
       $arr = split("-",$str);// splitting the array
       $yy = $arr[0];         //first element of the array is year
       $mm = $arr[1];         //second element is month
       $dd = $arr[2];         //third element is days
       if( checkdate($mm, $dd, $yy) ); {
          return true;
       }
   }
   else {
       $this->form_validation->set_message('validdate', 'Check format of %s field.');
       return FALSE;
   }

Monday, August 15, 2011

Code Igniter Date Validation Function

These two functions i use to validate maximum and minimum values of a date field


FUNCTION MAXDATE:
Function Name  : maxDate
Parameters     :$str,$reference,$refName

Meaning :
 $str : This variable is used to pass the variable name used to post the value to be validated
 $reference : This variable is used to pass the value of date that should be the allowable maximum date.
$refName : This variable is used to pass the name of reference, is Optional
Usage: 
Can be used in two ways
      1.   As call back function to the validation rules of Codeigniter
      Example: 
         $this->form_validation->set_rules('sessionDate['.$i.']','Date', 'trim|callback_maxDate['.$endDate.']|xss_clean');
      2.   As function Call
                  if(!maxDate('startDate','2011-06-23','End Date')){
             echo 'Satrt Date Should be Before End Date';
         }
---------------------------------------------------------------------
function maxDate($str,$reference,$refName='Reference Date'){
if ( !preg_match('/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/', $reference) ) {
//WRONG REFERENCE DATE FORMAT
$this->form_validation->set_message('maxDate', $refName.' is in Unknown Format');
//echo $refName.' is in Unknown Format';
return false;
}
else if ( !preg_match('/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/', $str) ) {
//WRONG DATE FORMAT
$this->form_validation->set_message('maxDate', 'The %s shoyuld be in "YYY-MM-DD" Format.');
//echo 'The %s shoyuld be in "YYY-MM-DD" Format.';
return false;
}
        
$arr = explode("-", $str);    // splitting the array
$yyyy = $arr[0];            // first element of the array is year
$mm = $arr[1];              // second element is month
$dd = $arr[2];              // third element is days
if( !checkdate($mm, $dd, $yyyy) ){
$this->form_validation->set_message('maxDate', 'The %s is an Invalid Date.');
//echo 'The %s is an Invalid Date.';
return false;
}
else if(strtotime($str)>strtotime($reference)){
$this->form_validation->set_message('maxDate', 'The Maximum value of %s should be '.$reference.'.');
//echo 'The Maximum value of %s should be '.$reference.'.';
return false;
}

//echo $this->form_validation->set_message('maxDate', 'The %s is an Invalid Date.');
return true;
    }
--------------------------------------------------------

Wednesday, July 6, 2011

Decimal validation using codeigniter form validation class | DSCRIPTS

Decimal validation using codeigniter form validation class | DSCRIPTS: "class MY_Form_validation extends CI_Form_validation {
 
    function decimal($value)
    {
        $CI =& get_instance();
        $CI->form_validation->set_message('decimal',
            'The %s is not a valid decimal number.');
 
        $regx = '/^[-+]?[0-9]*\.?[0-9]*$/';
        if(preg_match($regx, $value))
            return true;
        return false;
    }
}"

Tuesday, July 5, 2011

JavaScript: Avoid ajax if not necessary and store small data locally in the page itself


Avoid ajax if not necessary and store small data locally in the page itself.
Example Case:We have to custom messages or descriptions on selecting an option of dropdown.
We can use some attribute like title inside the option tag of select/ Dropdown list to store some custom values/ descriptions and can be used to display the message or text without AJAX.


Here i used the following code for storing the currency of each country in the title field of the corresponding option and will be displayed when the country is selected.
HTML CODE


<table width="100%" class="noBorder" cellpadding="0" cellspacing="0">
      <tr>
        <td>
<select name="hostCountry" onchange="showhostcurrency(this);">
            <option value="">COUNTRY</option>
            <option title="Rupees" value="1">INDIA</option>
            <option title="USD" value="1">USA</option> 
</select>
        </td>
        <td class="showCurrency">
        </td>
</tr>
</table>



function showhostcurrency(obj){
//Here the object will be passed to function which will be recieved to variable obj
//Value stored in title can be accessed as follows
     var currency=$(obj).find("option:selected").attr('title');
     if(currency!=''){
         var currency='Currency: '+currency;
     }
     $(obj).parent().parent().find('td.showCurrency').html(currency);
}

Monday, July 4, 2011

Custom Functions


I have been using PHP, Javascript, Jquery with codeignitor for the past 2 years. I used to use and make many custom functions for my productions purpose of which some are noteworthy and may be useful for others also.
I would like to share and discuss such custom functions with all PHP developers and freshers