The Answer To Life, The Universe and Everything
Written on October 21, 2009, by Mehmetali Shaqiri.

One quiet morning, while going through the motions of my daily routine – drinking coffee with my fellow programmers, I got a call from a client who said:

I just checked our vacancies page and it sucks, we don’t have an online form where users would submit their information but instead they have to fill the form locally and then send it to us by mail or fax. We have to improve this fast. I need this for tomorrow!

So I drank my coffee and started brainstorming on how I could accomplish this task the best way I could, always keeping in mind that I would have to finish it during the day. The task was peace of cake, I could do it in two hours, but the challenge was on UI. How to make it more dynamic (allowing users to enter multiple previous job positions, multiple phone numbers, multiple addresses etc.) and give users a greater experience on using the app. I wanted to accomplish this with no postbacks at all.

So in this case, the answer to life, the universe, and everything for me it was jQuery.

You’ve probably heard about jQuery, The Write Less, Do More JavaScript Framework. For those who didn’t have the chance to get their hands into jQuery, let me summarize it for you:

And without further ado, let’s do that voodoo that we do do so well.

Below you have a screenshot of the above scenario.

jQuery Life Saviour
jQuery Life Saviour

As you can see, the job position and company name are added based on user desire and are appended dynamically to the DOM. Initially I’ve defined only the FamilyName and the FirstName of the applicant. Then I’ve defined the container workContainer in which after the DOM is ready, are initialized the first controls
[ updated ]

<% using (Html.BeginForm("Result", "Home"))
       { %>
        <fieldset>
            <legend>Your Information</legend>
            <table>
                <tr>
                    <td align="right" valign="top">
                        Family Name:
                    </td>
                    <td align="left" valign="top">
                        <%=Html.TextBox("FamilyName", "", new { @class = "txt", style = "width: 200px" })%>
                    </td>
                </tr>
                <tr>
                    <td align="right" valign="top">
                        First Name:
                    </td>
                    <td align="left" valign="top">
                        <%=Html.TextBox("FirstName", "", new { @class = "txt", style = "width: 200px" })%>
                    </td>
                </tr>
                <tr>
                    <td align="right" valign="top">
                        ...
                    </td>
                    <td align="left" valign="top">
                        ...
                    </td>
                </tr>
                <tr>
                    <td align="right" valign="top">
                        ...
                    </td>
                    <td align="left" valign="top">
                        ...
                    </td>
                </tr>
                <tr>
                    <td align="right" valign="top">
                        Work Experience?
                    </td>
                    <td align="left" valign="top">
                        <div id="workContainer">
                        </div>
                    </td>
                </tr>
            </table>
            <%= Html.AntiForgeryToken() %>
            <p>
                <input type="submit" value="Apply For this Job" />
            </p>
        </fieldset>
    <%} %>
<script type="text/javascript">            
	//wait until DOM is ready
	$(function() {
 
		//prepare initial controls
		$('<table id="tblWork"><thead><tr><th>Position</th><th>Company</th><th>&nbsp;</th></tr></thead><tbody><tr><td><input type="text" name="position" /></td><td><input type="text" name="company" /></td><td>&nbsp;</td></tr></tbody></table>')
			.append('<a href="#" id="addAnother" class="add">Add Another</a>')
			.prependTo('#workContainer');                    
 
		//atach an event handler to the addAnother link
		$("#addAnother").click(function() {
			  //get the whole table                                           
			  var $tblWork = $("table#tblWork");                      
 
			  //add row at the end of the table
			  $("table#tblWork tr:last").after('<tr><td><input type="text" name="position" /></td><td><input type="text" name="company" /></td><td>&nbsp;</td><td><a href="#" class="delete">Remove</a></td></tr>');
 
			  //find all links with "delete" class and atach the handler
			  $tblWork.find('a.delete').click(function() {              
				//remove the current table row                                      
				$(this).parent().parent().remove();
			  });                      
 
		});            
	});            
 
</script>

The classes defined in this project are Applicant and WorkExperience.

namespace jQueryLifeSaviour.Entities
{
    public class WorkExperience
    {
        public string Position { get; set; }
        public string Company { get; set; }
    }
}
namespace jQueryLifeSaviour.Entities
{
   public class Applicant
    {
        public string FamilyName { get; set; }
        public string FirstName { get; set; }
        public List&lt;WorkExperience&gt; Experience { get; set; }
    }
}

And here is the action which occurs after you click on Apply for this job button.

/// Get user input posted by view.
/// Accepts only POST HTTP Methods,
/// although in this case the GET would be just fine since we are not dealing with sensitive data
///The collection of posted form elements
/// The current view (in this case Result)
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Result(FormCollection form)
{
     //create a new intance of Applicant class
     Applicant obj = new Applicant
     {
          FamilyName = form["FamilyName"],
          FirstName = form["FirstName"],
          Experience = new List&lt;WorkExperience&gt;()
     };
 
     //hold all input fields regarding company info
     string[] companies = form.GetValues("company");
 
     //hold all input fields regarding job position
     string[] positions = form.GetValues("position");
 
     //iterate through posted work experience and fill the WorkExperience list
     for (int i = 0; i &lt; positions.Length; i++)
     {
          obj.Experience.Add(new WorkExperience
          {
               Position = (positions[i]),
               Company = companies[i]
          });
      }
      ViewData["Applicant"] = obj;
      return View();
}

I’ve been using jQuery for a while and it made me realize that life is so much easier when using jQuery. With jQuery, JavaScript is no more “the necessary evil”, it’s even fun to code with.

You can download the full project here. This demo is developed on ASP.NET MVC 1.0 Framework, so you must install it in prior, otherwise you want be able to open it.

  • hajan

    I have started using JQuery about 6 months ago, building Insurance web-based application on the company I’m currently working… At the very beginning I was like “It would be better to get back to use plain javascript, same as I did before…” because I didn’t have much time to learn JQuery and to accomplish the project for the given deadline, but after 2 days I just realized that We could even finish the project much faster if we use JQuery, and it came out true… Few of the reasons are already mentioned in this post :)

    Nice entry Mehmetali…

  • http://spartansoft.org Mehmetali Shaqiri

    When I first started using jQuery I was amazed by how great it handles DOM manipulation and especially because of the separation of functionality (the “behavior layer”) from a Web page’s structure/content and presentation => Unobtrusive JavaScript. It is very elegant and fast, really fast.

    I was really surprised that no one made a presentation about jQuery in the Software Freedom Kosova Conference.

    Thnx for the comments Hajan.

  • hajan

    I definitely agree with your thoughts.

    Regarding Software Freedom Kosova Conference, I’m not very surprised coz (as I remember) it wasn’t mentioned even in DevReach (as per the schedule) this year in Sofia, Bulgaria.

    Anyway, It’s still quite new library and will have its time in the near future, let it be your motive to prepare some good JQuery lecture for some of the upcomming conferences and Tech. events near here and earn some good points by speaking about JQuery..

    Greets…

blog comments powered by Disqus

1,596 views

© Copyright Phalanx Blogosphere - Powered by Wordpress - Phalanx logo is designed by Leopard Cana