jQuery tips

We often write traditional code by not knowing limitations and performance issues. In this post, I’m going to discuss few concepts of jQuery with which you can increase performance of those methods.

It is always preferable not to interact with the DOM more frequently. This reduces the performance. For example:

var divs = "";
for (var i = 0; i < total; i += 1) {
    divs += "<div>" + i + "</div>";
}

$("#someId").html(divs);



Consider that there are 10000 records and you are calling the DOM selector every time when something new is appended. By calling so, you are absolutely decreasing the performance of your code. Instead, we can do that as coded above. In the above code what we are doing is, we first render all the records and in the end we are attaching those records to the DOM selector just once in the end. This increases the performance of the code. Alternatively, we can also achieve this using array. For example:

var divs = [];
for (var i = 0; i < total; i += 1) {
    divs.push("<div>" + i + "</div>");
}

$("#someId").html(divs.join(""));



Secondly, many times we get confused when to use find() method and when to use filter() method. SO let’s get into it.

Always remember that find() method looks for descendants or children and this method is useful to find child type of access. Let’s take an example:

<ul class="people">
    <li class="publisher">jQuery</li>
    <li class="publisher">O'Reilly</li>
    <li class="owner">Tim O'Reilly</li>
</ul>
var $names = $(".people li");
var $pubs = $names.find(".publisher");



In the above example, we won’t get any output because there are no child elements for li. Instead, using filter() method gives appropriate result. Hence the code:

var $names = $(".people li");
var $pubs = $names.filter(".publisher");



That’s all for now. In the coming posts, we go ahead with few more tips and tricks on both jQuery and JavaScript.

-By
Uma Maheswar
Helical It Solution

Get form data as an object using jQuery

Get form data as an object using jQuery

jQuery has an inbuilt method serializeArray which returns the form data in the form of an array. But at times, we require the data in form of an object. For example, consider the following form:

<form id="myForm">
    <input type="text" name="firstName" value="John">
    <input type="text" name="lastName" value="Doe">
    <input type="email" name="email" value="johndoe@example.com">
</form>

Now $('#myForm').serializeArray() would result in the following:

[
    {
        name:"firstName",
        value:"John"
    },
    {
        name:"lastName",
        value:"Doe"
    },
    {
        name:"email",
        value:"johndoe@example.com"
    }
]

But sometimes we require it as an object:

{
    firstName : "John",
    lastName :"Doe",
    email : "johndoe@example.com"
}

I know we can iterate over the serialized array and create the object but wouldn’t it be great if jQuery had this functionality built in?

I made a simple script that can be used to add this functionatily to jQuery:

jQuery.fn.serializeObject = function(){
    var results = {},
        arr = this.serializeArray();
    for (var i = 0, len = arr.length; i < len; i++) {
      obj = arr[i];
      //Check if results have a property with given name
      if (results.hasOwnProperty(obj.name)) {
        //Check if given object is an array
        if (!results[obj.name].push) {
          results[obj.name] = [results[obj.name]];
        }
        results[obj.name].push(obj.value || '');
      } else {
        results[obj.name] = obj.value || '';
      }
    }
    return results;
}

usage: $('#myForm').serializeObject()

Note: The reason behind using serialzeArray inside our snippet, despite the overhead is that it already handles multiselect(s) and checkboxes robustly, thus making our job easier.