Thursday 17 July 2014

Update google map location on click with jquery

Google maps can provide you directions, interactive maps, and satellite/aerial imagery of many countries. Maps can also search by keyword such as type of business.In this blog post, am sharing with you the code snippet which can help you to display google maps inside html DIV. I will also create multiple location links with location names, and on click of link, it will update the DIV with location in map.

here we load jQuery and google maps library from CDN.

<script src="http://code.jquery.com/jquery-1.11.0.min.js"> </script>
<script src ="http://maps.googleapis.com/maps/api/js?sensor=false&extension=.js"> </script>

We first create HTML like below code and we assign "div"  with id "googleMap" as below.

<h1>Jquery for Multiple Click Map</h1>
<div id="googleMap" style="width:500px;height:380px;"></div>

Three anchor tags with unique id. so that we can update map location inside HTMl div, when user click's on any link.

<a id="miami" href="#">Miami Link</a>
<a id="shaven" href="#">South Haven Link</a>
<a id="troy" href="#">Troy Link</a>

Here is the JAVASCRIPT that will do the job for you.

<script type="text/javascript">
function map1()
{
var mapTroy = {
  center:new google.maps.LatLng(42.5803,-83.1431),
  zoom:10,
  mapTypeId:google.maps.MapTypeId.ROADMAP
  };
var map=new google.maps.Map(document.getElementById("googleMap"), mapTroy);
}



function map2()
{
  var mapMiami = {
  center:new google.maps.LatLng(25.7877,-80.2241),
  zoom:10,
  mapTypeId:google.maps.MapTypeId.ROADMAP
  };
  var map=new google.maps.Map(document.getElementById("googleMap"), mapMiami);
}


function map3()
{
  var mapSouthHaven = {
  center:new google.maps.LatLng(42.4031,-86.2736),
  zoom:10,
  mapTypeId:google.maps.MapTypeId.ROADMAP
  };
  var map=new google.maps.Map(document.getElementById("googleMap"), mapSouthHaven);
}

google.maps.event.addDomListener(window, 'load', map2);



$(document).ready(function(){
    $('#miami').click(function() {        
      map2();
    });
   
    $('#shaven').click(function() {
     map3();
    });
    
    $('#troy').click(function() {
     map1();
    });
}); 

</script>

DEMO : http://jsfiddle.net/zP746/

Tuesday 15 July 2014

Drag-drop shopping cart example with ADD, REMOVE

Shopping cart example using draggable plugin -  jQuery EasyUI framework.

What is jQuery EasyUI framework ?

jQuery EasyUI offers a full collection of components including powerful datagrid, treegrid, panel, combo and more for building cross-browser web page. Users can use them all together, or just use some components he wants.
  • easyui is a collection of user-interface plugin based on jQuery.
  • easyui provides essential functionality for building modern, interactive, javascript applications.
  • using easyui you don't need to write many javascript code, you usually defines user-interface by writing some HTML markup.
  • complete framework for HTML5 web page.
  • easyui save your time and scales while developing your products.
  • easyui is very easy but powerful.
Detailed Info and Tutorials here: http://www.jeasyui.com/

First we load our easyUI javascript's and stylesheets, and create a table to represent the cart structure,like below.

HTML:

<html style="height:100%">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Building a drag-drop shopping cart - jQuery EasyUI Demo</title>
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/demo/demo.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
</head>
<body style="height:100%;">
<h2>Shopping Cart</h2>
<div class="easyui-panel" fit="true" border="false" style="height:100%;overflow:hidden">
<div class="cart">
<div class="ctitle">Shopping Cart</div>
<div style="background:#fff">
       
<table id="cartcontent" fitColumns="true" style="width1:300px;height:auto;">
<thead>
<tr>
<th field="name" width=140>Name</th>
<th field="quantity" width=60 align="right">Quantity</th>
<th field="price" width=60 align="right">Price</th>
<th field="remove" width=100 align="right">Remove</th>                
</tr>
</thead>
</table>
</div>
<div class="ctitle" style="position:absolute;bottom:10px">Drop here to add to cart</div>
</div>
<div class="products">
<ul>
<li>
<a href="#" class="item">
<img src="http://placehold.it/180x180"/>
<div>
<p>Balloon</p>
<p>Price:$25</p>
</div>
</a>
</li>
<li>
<a href="#" class="item">
<img src="http://placehold.it/180x180"/>
<div>
<p>Feeling</p>
<p>Price:$25</p>
</div>
</a>
</li>
<li>
<a href="#" class="item">
<img src="http://placehold.it/180x180"/>
<div>
<p>Elephant</p>
<p>Price:$25</p>
</div>
</a>
</li>
<li>
<a href="#" class="item">
<img src="http://placehold.it/180x180"/>
<div>
<p>Stamps</p>
<p>Price:$25</p>
</div>
</a>
</li>
<li>
<a href="#" class="item">
<img src="http://placehold.it/180x180"/>
<div>
<p>Monogram</p>
<p>Price:$25</p>
</div>
</a>
</li>
<li>
<a href="#" class="item">
<img src="http://placehold.it/180x180"/>
<div>
<p>Rolling</p>
<p>Price:$25</p>
</div>
</a>
</li>    
       
</ul>
</div>
</div>

</body>
</html>

It's time for Javascript action. 

JAVASCRIPT:
$(function(){

 // we call datagrid function on table we created in HTML.

$('#cartcontent').datagrid({
singleSelect:true,
showFooter:true
});

  // on elements with class "item", draggable method to specify it as draggable.

$('.item').draggable({
revert:true,
proxy:'clone',
onStartDrag:function(){
$(this).draggable('options').cursor = 'not-allowed';
$(this).draggable('proxy').css('z-index',10);
},
onStopDrag:function(){
$(this).draggable('options').cursor='move';
}
});


  // on elements with class "cart", droppable method to drop area.

$('.cart').droppable({
onDragEnter:function(e,source){
$(source).draggable('options').cursor='auto';
},
onDragLeave:function(e,source){
$(source).draggable('options').cursor='not-allowed';
},
onDrop:function(e,source){
var name = $(source).find('p:eq(0)').html();
var price = $(source).find('p:eq(1)').html();
addProduct(name, parseFloat(price.split('$')[1]));
                }
});

         
});


        function remove(rowID,rowIndex){
          $('tr#'+rowID).remove();
             var dg = $('#cartcontent');
            dg.datagrid('deleteRow', rowIndex);
         
          setTimeout(function(){
             dg.datagrid('reload');
       dg = $('#cartcontent');
var data = dg.datagrid('getData');
            var rows = dg.datagrid('getRows');
     
           
function add(){
for(var i=0; i<data.total; i++){
                    var row = data.rows[i];
if (row.name == name){
row.quantity += 1;
return;
                    }
}
data.total -= 1;

}
add();
dg.datagrid('loadData', data);
            dg.datagrid('reload');
var cost = 0;

for(var i=0; i<rows.length; i++){
           
cost += rows[i].price*rows[i].quantity;
            }
dg.datagrid('reloadFooter', [{name:'Total',price:cost}]);
                     $('.remove').click(function() {
                      var rowID= $(this).closest('tr').attr('id');
                      var rowIndex= $(this).attr('id');
                      remove(rowID,rowIndex);
                    });
         
          },1000);
        }
     
function addProduct(name,price){
var dg = $('#cartcontent');
var data = dg.datagrid('getData');
function add(){
for(var i=0; i<data.total; i++){
var row = data.rows[i];
if (row.name == name){
row.quantity += 1;
return;
}
}

data.rows.push({
name:name,
quantity:1,
price:price,
                  remove:'<a id="'+data.total+'" class="remove" href="javascript:;">remove</a>'
                });
              data.total += 1;
}
add();
dg.datagrid('loadData', data);
var cost = 0;
var rows = dg.datagrid('getRows');
for(var i=0; i<rows.length; i++){
cost += rows[i].price*rows[i].quantity;
}
dg.datagrid('reloadFooter', [{name:'Total',price:cost}]);
                    $('.remove').click(function() {
                      var rowID= $(this).closest('tr').attr('id');
                      var rowIndex= $(this).attr('id');
                      remove(rowID,rowIndex);
                    });        
}

DEMO Link http://jsbin.com/defeqogu/4

Fancybox video in pop up

In this post, we are going to display videos in fancy box pop up. we can navigate between video, using next and previous button. This small code snippet should help you for displaying videos.

First Include fancy box from CDN links as below

<script src="http://fancyapps.com/fancybox/source/jquery.fancybox.js" type="text/javascript"/>
<script src="http://fancyapps.com/fancybox/source/jquery.fancybox.css" type="text/javascript"/>

Construct HTML to show the video:

                <div id="carousel">
                    <div>
                        <a class="fancybox" rel="arch" data-fancybox-type="iframe" href="http://www.youtube.com/embed/L9szn1QQfas">
                           <img src="http://fancyapps.com/fancybox/demo/2_s.jpg" alt=""/>
                        </a>
                    </div>
                    <div>
                        <a class="fancybox" rel="arch" data-fancybox-type="iframe" href="http://www.youtube.com/embed/cYplvwBvGA4">
                            <img src="http://fancyapps.com/fancybox/demo/1_s.jpg" alt=""/>
                        </a>
                    </div>
                    <div>
                        <a class="fancybox" rel="arch" data-fancybox-type="iframe" href="http://www.youtube.com/embed/L9szn1QQfas">
                           <img src="http://fancyapps.com/fancybox/demo/2_s.jpg" alt=""/>
                        </a>
                    </div>
                    <div>
                        <a class="fancybox" rel="arch" data-fancybox-type="iframe" href="http://www.youtube.com/embed/cYplvwBvGA4">
                           <img src="http://fancyapps.com/fancybox/demo/1_s.jpg" alt=""/>
                        </a>
                    </div>
                    <div>
                        <a class="fancybox" rel="arch" data-fancybox-type="iframe" href="http://www.youtube.com/embed/L9szn1QQfas">
                           <img src="http://fancyapps.com/fancybox/demo/2_s.jpg" alt=""/>
                        </a>
                    </div>
                </div>

CSS:
// style our iframe.
.fancybox-type-iframe .fancybox-nav {
    width: 10%;
    height: 70%;
    margin: 15% 0;
}

JS:

// apply fancybox as below, on all the links which has class "fancybox".
 
$(".fancybox").fancybox();

Here is code and demo http://jsfiddle.net/TWXq9/4/

Ruby on rails - E-mail template customize sample code.

How can i send the details of the model object into the mailer from particular controller ?
 
I have 2 models po and send.

Associations are as give below.
 
po: has_many sends
send: belongs_to po


Controller:
class SendsController < ApplicationController

def create
 @send = Send.new(params[:send])
 if @send.save
   Pomailer.registration_confirmation(@send.po).deliver
   flash[:success] = "Send mail"
   redirect_to capax_path
 else
   flash[:warning] = "mail not send"
   redirect_to capax_path
 end 
 
end  
Mailer
class Pomailer < ActionMailer::Base 
 
 default from: "from@example.com"
 def registration_confirmation(po)
  @po = po
  mail(:to => "xyz@yahoo.co.in", :subject => " New purchase order send by " )
 end
 
end 
In views create a Pomailer folder and add a file registration_confirmation.html.erb
In Below code you can customize your E-mail template design.
 
<!DOCTYPE html>
<html>
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
 </head>
 <body>
  <h1>Dear <%= @po.vname %></h1>,
   <p>
   You have purchase order with invoice no <%= @po.invoiceno %>.
   </p>
  <p> 
  ......
   add your required information using @po object.
  .....
  </p>
  <p>Thanks !</p>
</body>
</html>

Autocomplete with two input boxes- jquery

There are situations where you want to apply autocomplete on two  different input boxes.
Below is the code which does exactly the same.

Construct your Html:
<input type="text" id="txtPartNum" class="autosuggest" />
<input type="text" id="txtPartNum2" class="autosuggest" />

Javascript:
 
// load js libraries from CDN. 
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>  
 
<script type="text/javascript"> 
  // on load of page, invoke SearchText() function.
  //which will apply autocomplete on input boxes with class "autosuggest". 
  $(document).ready(function () {
        SearchText();
  }); 
 
   // Function finds all input boxes with class "autosuggest" and applies autocomplete on it.
  function SearchText() {
    $(".autosuggest").autocomplete({
       select:function(event, ui){
       window.location.href = '/Products/ProductInfoCenter.aspx?partnum=' + ui.item.value;
      },
      source: function (request, response) { 
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/test.aspx/GetAutoCompleteData",
            data: "{'PartNumber':'" + $(this.element).val() + "'}",
            dataType: "json",
            success: function (data) {
               response(data.d);
            },
            error: function (result) {
                alert(err.message);
            }
        });
      }
    });
  }
</script>
    //Server side i am using C# as below: it returns JSON data as response.
    [WebMethod]
    public static List<string> GetAutoCompleteData(string term)
    {
            List<string> result = new List<string>();
            OdbcConnection conn = new OdbcConnection(DB.DatabaseConnString());
            string query = "SELECT * from gallery WHERE (unique_no LIKE '%" + NJS_Helper.FormatStringforDB(term) + "%') limit 5;";
            if (conn.State == ConnectionState.Open)
                conn.Close();
            conn.Open();            
            OdbcDataReader dataReader = new OdbcCommand(query, conn).ExecuteReader();
            if ((dataReader != null) && (dataReader.HasRows))
            {
                while (dataReader.Read())
                {
                    result.Add(dataReader["unique_no"].ToString());
                }
            }
            dataReader.Close();
          return result;
    } 

Asp.net C# Webmethod with jquery

I am using webmethod with Jquery.
CLIENT SIDE:
1. Include jquery like below example script 
<script type='text/javascript' src="http://code.jquery.com/jquery-1.11.1.min.js"/>  
2. I have a input box with id txttest.
<input type="text" id="txttest" class="autosuggest" /> 
3. Ajax call as below.  
  $.ajax({
       type: "POST",
       contentType: "application/json; charset=utf-8",
       url: "order_form.aspx/GetAutoCompleteData", 
       data: '{DocName: "' + $("#txttest").val() + '" }', 
       dataType: "json",
       success: function(data) { 
           //response(data.d);   
           alert('success');
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) { 
         alert(textStatus);
       } 
   }); 
4. On success you will get data from server [Example: response(data.d);]  
SERVER SIDE:
1. Example web method as below:
    [WebMethod]
    public static List<string> GetAutoCompleteData(string term)
    {
       List<string> result = new List<string>();
       OdbcConnection conn = new OdbcConnection(DB.DatabaseConnString());
       string query = "SELECT * from gallery WHERE (unique_no LIKE '%" + NJS_Helper.FormatStringforDB(term) + "%') limit 5;";
       if (conn.State == ConnectionState.Open)
       conn.Close();
       conn.Open();            
       OdbcDataReader dataReader = new OdbcCommand(query, conn).ExecuteReader();
            if ((dataReader != null) && (dataReader.HasRows))
            {
                while (dataReader.Read())
                {
                    result.Add(dataReader["unique_no"].ToString());
                }
            }
      dataReader.Close();
      return result;
    }