Wednesday, July 24, 2013

Apply Even and Odd classes for elements on, "while" or "for" loop

When we display list of elements using any looping, we need to add some two classes for differentiate one row from another. On this case we need use one extra variable, and increment it throw loop, then we can get '0' or '1' by mod(%) this value. So now we can have two different classes repeatedly like 'r0','r1'. And now write style for these two classes.

Example:
<style type="text/css">
Output
.list0{
background-color: #00B2C1;
}
.list1{
background-color: #50D4FF;
}
</style>
<html>
<title>Even and Odd classes for loopig elements</title>
<body>
<table cellspacing="0">
<tr>
<td>NO</td>
<td>Name</td>
</tr>
<?php $i=0; while($i<=10) { ++$i; ?>
<tr class="list<?php echo (++$x%2); ?>">
<td><?php echo $i; ?></td>
<td>Name <?php echo $i; ?></td>
</tr>
<?php } ?>
</body>
</html>


Note: Here we can use '$i' to mod. But most of cases we don't has this option, and more over here we wrote single line(++$x%2) to get mod value.

Monday, July 22, 2013

Regular Expression validation for frontend(JS) and backend(PHP)

Start with one example:

For validate Name Field: Alphabets, numbers and space(' ') no special characters min 3 and max 20 characters.

var ck_name = /^[A-Za-z0-9 ]{3,20}$/; 
if (!ck_name.test(name))
{
        alert('Enter valid Name.');
        return false;
}


Note: The above code for front end using JavaScript. If you are using PHP use key word preg_match instead of test.

Some important conditions:
[abc] Find any character between the brackets
[^abc] Find any character not between the brackets
[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase z
{3,10} Check for the string length in between give boundary.


Important Links:


Wednesday, July 10, 2013

Implement "Remember Me" option for login using Javascript(JQuery) cookies

1. Get JQuery Cookie library in hand

To implement this first you need to have JQuery Cookie library. So please save following JS file as "jquery.cookie.js", or you can directly download from Github .

//Save it as jquery.cookie.js
/*!
 * jQuery Cookie Plugin v1.3.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
 if (typeof define === 'function' && define.amd) {
  // AMD. Register as anonymous module.
  define(['jquery'], factory);
 } else {
  // Browser globals.
  factory(jQuery);
 }
}(function ($) {

 var pluses = /\+/g;

 function raw(s) {
  return s;
 }

 function decoded(s) {
  return decodeURIComponent(s.replace(pluses, ' '));
 }

 function converted(s) {
  if (s.indexOf('"') === 0) {
   // This is a quoted cookie as according to RFC2068, unescape
   s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
  }
  try {
   return config.json ? JSON.parse(s) : s;
  } catch(er) {}
 }

 var config = $.cookie = function (key, value, options) {

  // write
  if (value !== undefined) {
   options = $.extend({}, config.defaults, options);

   if (typeof options.expires === 'number') {
    var days = options.expires, t = options.expires = new Date();
    t.setDate(t.getDate() + days);
   }

   value = config.json ? JSON.stringify(value) : String(value);

   return (document.cookie = [
    config.raw ? key : encodeURIComponent(key),
    '=',
    config.raw ? value : encodeURIComponent(value),
    options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
    options.path    ? '; path=' + options.path : '',
    options.domain  ? '; domain=' + options.domain : '',
    options.secure  ? '; secure' : ''
   ].join(''));
  }

  // read
  var decode = config.raw ? raw : decoded;
  var cookies = document.cookie.split('; ');
  var result = key ? undefined : {};
  for (var i = 0, l = cookies.length; i < l; i++) {
   var parts = cookies[i].split('=');
   var name = decode(parts.shift());
   var cookie = decode(parts.join('='));

   if (key && key === name) {
    result = converted(cookie);
    break;
   }

   if (!key) {
    result[name] = converted(cookie);
   }
  }

  return result;
 };

 config.defaults = {};

 $.removeCookie = function (key, options) {
  if ($.cookie(key) !== undefined) {
   // Must not alter options, thus extending a fresh object...
   $.cookie(key, '', $.extend({}, options, { expires: -1 }));
   return true;
  }
  return false;
 };

}));



2. Add "Remember Me" check box on Login page

Add "Remember Me" check box in login form, then include "jquery.cookie.js" and your JS file (here: login.js).

<input type="text" id="username" /><br />
<input type="password" id="password" /><br />
<input type="checkbox" id="c1" />Remember Me<br />
<input type="submit" id="loginsubmit" />
.
.
.
<script src="js/jquery.cookie.js"></script>
<script src="js/login.js"></script>


3. Set and Get Cookie using JQuery

Now, set entered username on cookie, or display username if already avail on cookie. To do this,
include following line in your JS file (here: login.js)

$(document).ready(function()
{

// Please read these set of code after you read next set. So that you can understand simply.
var username=$.cookie("username");   // Get username from cookie on form load.
if(username!=undefined)
{
$('#loginsubmit').val(username);   // Display username on input box if avail on cookie.
      $('#c1').prop('checked', true);  // Check check box manually by us. So that duration for current email will reset.
}

// Read this set first.
$('#loginsubmit').click(function()
{
      if($('#c1').is(':checked')) // If user checked remember me check box
{
                var email=$('#loginsubmit').val(); // Get entered username or email
                //  Set username on cookie when login form submit.
$.cookie("username", email, { expires: 365 });  // Remember username for 1 year.
}
      // Your other codes...
}

});


Note:
1. Assign username or email to cookie after you done form validation like email validation, empty checking, so that you can sure for stored value are original.

2. And here we set username or email on cookie for one year. You don't need to worry about like "will expire after one year?". Because it will reset to one year whenever user try to login. And only go empty once if the user not login even one time for a year. You can change this duration as you need.

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...