All posts in Javascript

jquery plugin: List builder

I needed a simple jquery plugin that created a list bulder but could not fine one. So I came up with a very simple one that met the requirements. It’s not full featured, but it works. Feel free to fork on github.

Javascript, HTML5 Reading..

A colleague at work asked for some links to get up to speed on HTML5 and Javascript. Here is a small list to get started.

Sites (Free!)

HTML5

Javascript

Books (Not Free)

A Quick look at Modernizr’s feature detection.

I recently had a requirement to display the description of the textbox using the “placeholder” attribute. The problem, of course, is not all browsers support this. The fallback would be to display a label where “placeholder” is not supported.
Modernizr makes this easy.
From The Modernizr site:
“Modernizr uses feature detection to test the current browser against upcoming features like rgba(), border-radius, CSS Transitions and many more.”

It’s a pretty simple concept. Just add the modernizer script to the top of your webpage, then features are tested against the browser and allows the developer to write code based if that feature exists or not.

Take the following example:

html



<label for="txtsearch" id="lblSearch" style="display:none">Search products</label>
<input type="text" placeholder="Search products" id="txtsearch"/>
<input type="button" value="Go"/>

Javascript

 
if (!Modernizr.input.placeholder){
    //display the label where placeholder is not supported.
    $('#lblSearch').show();
}

As you can see the input textbox has a attribute placeholder=”Search products”. This will be ignored by browsers that do not support it. The javascript code uses the Modernizr feature detection and displays the label.
If you want to take advantage of modern browser features but still have to support older browsers, I strongly recommend you take a look at Modernizr .

Converting a JSON string to a .net Object

Overview

When building web apps we usually put our main functionality in a business layer. So lets say we have a website that lets our users add book suggestions. We will require the user to log into our site, so we know who the user is. To keep this simple we will have a form on that asks for the name of the book and a category. We will send this to our service, along with the user’s name and address using ajax.

The backend – Our .net classes

  • For this simple example, we will create three class objects: Address, Book, and BookSuggestion.
    Net Classes
    First we need the Address class:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace TestJSONObjects
    {
    	public class Address
    	{
    		public string Address1 { get; set; }
    		public string Address2 { get; set; }
    		public string City { get; set; }
    		public string State { get; set; }
    		public string Zip { get; set; }
    	}
    }
    

    Next we need Book.cs.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace TestJSONObjects
    {
    	public class Book
    	{
    		public string Name { get; set; }
    		public string Category { get; set; }
    	}
    }
    

    And finally the BookSuggestion class.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace TestJSONObjects
    {
    	public class BookSuggestion
    	{
    		public Address UserAddress { get; set; }
    		public Book SuggestedBook { get; set; }
    		public string UserName { get; set; }
    		public string Device { get; set; }
    	}
    }
    

  • The webpage

        
    	<form id="form1" runat="server">
        <input type="hidden" id="name" value="Kevin Gaddy" />
        <input type="hidden" id="Address1" value="123 Park Ave." />
        <input type="hidden" id="Address2" value="" />
        <input type="hidden" id="City" value="St. Louis" />
        <input type="hidden" id="State" value="MO" />
        <input type="hidden" id="Zip" value="12345" />
        <div>
            <h1>
                This is a Test</h1>
            <fieldset>
                <div>
                    <label id="lblName" for="txtBookName">
                        Book:</label>
                    <input type="text" id="txtBookName" />
                </div>
                <div>
                    <label id="lblCat" for="txtCategory">
                        Category:</label>
                    <input type="text" id="txtCategory" />
                </div>
          
                <div>
                </div>
            </fieldset>
        </div>
        </form>				
    

    As you can see we have some hidden fields that will hold the information that we collected when the user logged in. Next we have a form that will get the user’s book and category suggestion. Now we need to create the service that will collect the information.

  • I created a BookSuggestions.aspx to house our service method. Here is the code behind:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    namespace TestJSON
    {
    	public partial class BookSuggestions : System.Web.UI.Page
    	{
    		[WebMethod(EnableSession = true)]
    		public static void AcceptObjectandDoSomething(string jsonString)
    		{
    			TestJSONObjects.BookSuggestion bs = new TestJSONObjects.BookSuggestion();
    
    			JavaScriptSerializer serializer = new JavaScriptSerializer();
    			bs = serializer.Deserialize<TestJSONObjects.BookSuggestion>(jsonString);
    			
    			if (bs == null)
    			{
    			}
    			else
    			{
    			}
    
    		}
    
    	}
    }
    

    So you see our method, AcceptObjectandDoSomething(string jsonString) will just accept a string from the ajax call. The first line in our method:

    TestJSONObjects.BookSuggestion bs = new TestJSONObjects.BookSuggestion();
    

    This creates an instance of the BookSuggestion object. Now we create a JavaScriptSerializer instance called serializer: JavaScriptSerializer serializer = new JavaScriptSerializer(); Now we use the serializer instance to convert the string that came into the method to the BookSuggestion object.

    bs = serializer.Deserialize<TestJSONObjects.BookSuggestion>(jsonString);
    

  • Now we can write our javascript to send the data to the service call.Lets create some object that will mirror our c# .net classes:

    var address = function(address1, address2, city, state, zip) {
    	this.address1 = address1;
    	this.address2 = address2;
    	this.city = city;
    	this.state = state;
    	this.zip = zip;
    }
    
    var book = function(name, category) {
    	this.name = name;
    	this.category = category;
    }
        	  
    var suggestion = function(address, book, userName, device) {
    	this.suggestedBook = book;
    	this.username = userName;
    	this.device = device;
    	this.userAddress = address;
    }
    

    It’s important that these classes have the same property names as their .net counterparts. The Ajax Method:

    $(document).ready(function() {
    	$('#addtoform').live('click', function() {
    
    		var myBook = new book($('#txtBookName').val(), $('#txtCategory').val());
    
    		var myAddress = new address($('#Address1').val(), $('#Address2').val(), $('#City').val(), $('#State').val(), $('#Zip').val());
         	//console.dir(myAddress);
    		var mySuggestion = new suggestion(myAddress, myBook, $('#name').val(), 'ipad');
        	//console.dir(mySuggestion);
    				
    
    		var jsonText = JSON.stringify(mySuggestion);
    		$.ajax({ type: "POST", url: "BookSuggestions.aspx/AcceptObjectandDoSomething", data: "{'jsonString':'" + jsonText + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { console.dir(msg.d); } }); });
    }); 
    


    ajax

    post

    So you can see we are collecting the form info when the user clicks the #addtoform link.

    Now here is the important part:

    var jsonText = JSON.stringify(mySuggestion);

    posting This will make the javascript objects a JSON string that we can send to our service method. This is the string that the JavaScriptSerializer will convert to your business objects.


    incomming Source Code

Ubuntu – node.js install cheatsheet

See setting up ubuntu server cheat sheet.

sudo apt-get install g++ curl libssl-dev

sudo apt-get install git-core


git clone git://github.com/joyent/node

cd node
./configure
make
sudo make install

Install NPM (Node Package manager)

Isaac Schlueter suggests giving yourself permission to the “/usr/local directory instead of using sudo. You should read his post.

sudo chown -R $USER /usr/local


curl http://npmjs.org/install.sh | sh

Help:

npm help

Install:

npm install |your package|

A close look at the HTML5 Boilerplate

A close look at the HTML5 Boilerplate from yayQuery on Vimeo.

Intro to Pubsub

Rebecca on Pubsub from yayQuery on Vimeo.

Hello FuncUnit!

I have been looking for a good test suite for my javascript code for a while. Qunit has been great, but it still misses a lot when it comes to the functionality of the front end. While watching the presentation videos from the jQuery 2010 conference, I noticed FuncUnit was mentioned a lot. If you get a chance, check out Alex Sexton’s presentation on this and other tools that will help with jQuery and Javascript development.

FuncUnit is a free, open source, web application testing tool. Getting it setup was pretty straightforward. I was able to test a page, type text into a input field, and test the validation, all via javascript. I will try to post more on this tool as I am sure to use it more. In the meantime, If anyone knows how to select a Select Box value for testing, let me know.

Update

I figured out how to select an option in a selectbox:


S('#creditCartSelect option[value=Visa]').dblclick();

 
UA-21428743-1