Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Saturday, March 24, 2012

Enhance your HTML tables with DataTables jQuery Plugin

Who doesn’t like formatted HTML tables, especially when the table is large and you wish there was an easy way to format, enhance and search the data within. Well, look no further than DataTables. DataTables is a jQuery plugin that will essentially enable you to do just that.

Test Drive the table below:

 

$(document).ready(function() {
    $('#example').dataTable();
});​
You can disable features that you don’t wish to use.



$(document).ready(function() {
                $('#example').dataTable( {
                    "bPaginate": false,
                    "bLengthChange": false,
                    "bFilter": true,
                    "bSort": false,
                    "bInfo": false,
                    "bAutoWidth": false } );
            } );






The page controls which are used by default in DataTables (forward and backward buttons only) are great for most situations, but there are cases where you may wish to customize the controls presented to the end user. This is made simple by DataTables through its extensible pagination mechanism. There are two types of pagination controls built into DataTables: two_button (default) and full_numbers. To switch between these two types, use the sPaginationType initialization parameter.



$(document).ready(function() {
    $('#example').dataTable({"sPaginationType": "full_numbers"});
});​






You can create custom search/filter for each of the columns in the table:



            var asInitVals = new Array();
            
            $(document).ready(function() {
                var oTable = $('#example').dataTable( {
                    "oLanguage": {
                        "sSearch": "Search all columns:"
                    }
                } );
                
                $("tfoot input").keyup( function () {
                    /* Filter on the column (the index) of this element */
                    oTable.fnFilter( this.value, $("tfoot input").index(this) );
                } );
                
                
                
                /*
                 * Support functions to provide a little bit of 'user friendlyness' to the textboxes in 
                 * the footer
                 */
                $("tfoot input").each( function (i) {
                    asInitVals[i] = this.value;
                } );
                
                $("tfoot input").focus( function () {
                    if ( this.className == "search_init" )
                    {
                        this.className = "";
                        this.value = "";
                    }
                } );
                
                $("tfoot input").blur( function (i) {
                    if ( this.value == "" )
                    {
                        this.className = "search_init";
                        this.value = asInitVals[$("tfoot input").index(this)];
                    }
                } );
            } );
These are just a few features that I have personally worked with. There is a lot more you can do with the jQuery DataTable plugin. Checkout the full range of demos here

Thursday, May 26, 2011

Knockout JavaScript

 

Awesome presentation on Knockout JavaScript library by Steve Sanderson!

Knockout.js is a Open Source JavaScript Library. Knockout.js provides rich client-side interactivity even those not solved by jQuery. It provides a MVVM patern similar to Silverlight. Knockout does the following: dependency tracking, declarative binding, integrated templating.

image

image

Using ko.observable makes it possible to update the UI automatically when the view model changes. If you declare your model properties as observables, it will notify subscribers about changes.

image

image

dependentObservable updates the view model when the dependencies change.

image

image

In the above example when firstname or lastname changes, the changes are propagated automatically to Full Name.

Tracking Friends of Bert Smith:

Create a Constructor friend – any function can act as a constructor for a class.

image

Create an observableArray of friends which will notify the view model of changes.

image

Create a jQuery template to render the data.

image

Result:

image

Add a button to add “Another” friend and bind a click function to the view model.

<button data-bind=”click: addFriend”> Add Friend</button>

image

use push to add an element to an array.

Result:

image

Let’s track changes by adding a date element

image

Result: every time you add a friend, it reruns the whole template as you can see the time changes for all the elements in the template.

image

But with Knockout, we can update the DOM in a minimum way so that the template runs only for the new elements added.

image

Note that we are letting Knockout control the iteration for us. $each from the template is no longer needed.

Result:

image

Now let’s say you want to add and remove friends and want to make names of the friends you add editable.

So we will go back to the friends template and add a remove button and assign a “Remove” function on click. Also add an input box and data-bind it with the name of the friend function. Go back to the friend function and add a remove function as shown below.

image

Result:

image

Now say you want to track your friend if they were on twitter. If they are, you want display that using a check box and an textbox for their twitter name. Add isOnTwitter and twitterName to the friend function.

image

Go back to the friends template and add a checkbox and textbox with data-binding properties as shown below.

image

Result":

image

Now you may want the checkbox to appear only when the checkbox is checked.

image

Result:

image

The above functionality can also be achieved using adding a {{if …}} to a template, but that would mean the rendering the whole template every time the checkbox is clicked. With Knockout JavaScript, you can do this in a minimal way – just means faster, responsive apps.

Now I’d like to know the count of the numbers of friends I have.

image

Result:

image

Now I want to disable the Add friend button if there are more than 5 friends.

image

Result:

image

Now I’d like to save the data in JSON (JavaScript Object Notation) format. I can do that by sending an AJAX request to the server. ASP.NET has got a model binding for JSON its going to parse the data automatically by writing very little code. Add a save function to the view model as shown below. Note the use of $.ajax (jQuery) function to post my data to an action method of the MVC app called Save. Convert the data to JSON format using the ko object without observables to be sent to the server.

Add a save button and data-bind it to the save method of the model.

image

save method:

image

On the server, we need a controller to handle the request coming from the view. Note that no special parsing of JSON data is needed.

image

The person class closely resembles the JSON data structure MVC3’s JSON object binder can automatically does the binding for us. No special parsing is needed.

image

Result:

image

Thursday, May 19, 2011

JavaScript and jQuery

Good video on JavaScript and JQuery by John Resig



key learning for my future reference:
Prototype:
Prototype gives you basic 1:1 inheritance and lets you chain functions together.
function People(){}
People.prototype.human=true;

function Resig(name)
{
   this.firstName=name;
}

Resig.Prototype=new People();
Resig.Prototype.lastName="Resig";
var john = new Resig("John");

thus:
john is an instanceof Resig
john is an instance of People
john is an instance of Object

Closure:
function Ninja(){
  var slices=0;
  this.getSlices = function(){
     return slices;
   };
  this.slice=function(){
     slices++;
  };
var Ninja=new Ninja();
ninja.slice; //works
ninja.getSlices == 1; //works
ninja.slices; //does not work/exist

};
};


In the above example, if you try and access a variable external to a function, then it does not work because of the closure between that function and the variable.

In JavaScript, everything is passed as references.

Programming with DOM in JavaScript can be hard. DOM is an object representation of XML structure (in most cases an HTML document).

examples of programming with DOM:
<div> </div>
document.getElementsByTagName("div");

<div id="test"> </div>
document.getElementsById("test");

removeChild();
appendChild();
insertBefore();

..... hence the need for JavaScript Libraries like jQuery.JavaScript Libraries drastically simplifies DOM and Ajax animations.jQuery (open source) provides simplified APIs to do most of the difficult work in JavaScript by abstracting the user from the horrible cross-browser issues.

Example:
$("div").addClass("special");

$ is a jQuery Object.

jQuery is based on the CSS concept to locate elements to take action against them.

Example:
<div id="body">
  <h2> Some Header </h2>
  <div class="contents">
     <p> ... </p>
     <p> ... </p>
  </div>
</div>

$("div") ;
the above jQuery line selects all div tags.

$("#body");
find items by ID

$("div.contents");
find all div tags with class contents

jQuery has the best selector engine that most browsers support.Use jQuery to easily find things within the document to DO something against them.

$("div > div");
find all divs that are child of other divs.

$("div:has(div)");
custom selector returning all divs that have divs inside of them

After you find the element, what do you do next?
  • DOM manipulation (append, prepend, remove)
  • Events (click, hover, toggle)
  • Effects (hide, show, fadeIn, fadeOut)
  • AJAX (load, get, post)

$("a#open").click(function(){
   $("#menu").show();
   return false;
});

jQuery makes heavy use of anonymous functions.

Events:
$("form").submit(function(){
   if($("$input#name").val()=="")
      $("span.help".show());
});

$("a#open").click(function{
   $("#menu").show();
   return false;
});

Animations:
$("#menu".slideDown("slow"));

AJAX:
$("#body".load("sample.html div > h1"));

returns html:
<div id="body">
   <h1> Hello World! </h1>
</div>

$.getJSON("test.json", function(js){
   for (var name in js)
   $("ul").append("<li> + name + </li>");
});

Chaining:
Actions can be chained together in jQuery
$("div").hide(); //find.action
$("div").hide().css("color", "blue"); //find.action.action
$("div").hide().css("color", "blue").slideDown(); //find.action.action.action

Other benefits of using jQuery
  • fully documented
  • great community
  • tons of plugins
  • small size (14kb)
  • works cross-browsers

jQuery contains a lot of features from Python.Some of the other features include:

destructuring: breaking apart an object (including arrays), grabbing values out of them and transposing them.
[a, b, c]=[1, 2, 3];
is same as:
a=1;
b=2;
c=3;

array comprehension: populate an array of values
[a for (a=1; a<10; a++)]

new way to declare variables: 
let foo=5; // declares the variable foo within a block and not a function

books:

Sunday, April 24, 2011

Monday, April 4, 2011

jQuery and ASP.NET web forms

Here is a good Microsoft Webcast to get started with jQuery

My first jQuery code:












    <script type="text/javascript">
        $(document).ready(function () {
            $("#Button1").click(function () {
                var text = $("#Text1").val();
                alert(text);
            });

        });

more to come...

reference