Commonly used JQuery methods and snippets

It’s been a long time since I have written anything on my blog. I seriously feel that it is turning into an “update-only-when-I-have-time” kind of thing. I don’t like it, but can’t do anything. That’s the way life goes. Anyways, there is something I have to say about JQuery. I am very much impressed with it and the way it is making everybody’s life easier. It is like the social networking fever in the software development industry where everybody seems to be talking about JQuery, its plug-ins and trying to find new ways to use it in one way or the other. It is a good thing. I also use it whenever I see even a little room to insert JavaScript in web applications. I can’t recall when was the last time I used  document.getElementById():). JQuery is taking over the world. All we need to do is to keep up with its pace if we want to get ahead in web development business.

The thing which bothers me more than anything else whenever I use JQuery is the fact that it’s all scattered. A small number of commonly used JQuery methods are being used everywhere repeatedly without change. This is definitely not a problem with JQuery, but with me as I am a long time fan of putting all the JavaScript dirty stuff in one file. I guess the same can’t be achieved with JQuery for its methods are tightly coupled with the HTML elements on the page.

One might think what I am trying to achieve here. My intention is to have all the JQuery methods in one place so that I can come back to them whenever I need them. I know the JQuery documentation is there exactly for this purpose, but I guess that documentation is not control-driven rather functionality driven. For example if I am using a Dropdown control on my page and using JQuery want to find out its selected value, I have to undergo the same struggle I went the last time in order to figure out all the possible methods I can use to accomplish the task. How about creating a control driven JQuery wrapper that will wrap the functionality of JQuery library core methods? err…that was just of the top of my head.

May be my thinking is not legitimate and it is just a matter of spending more time around JQuery and I will start memorizing every bit of it. May be. Anyways, for the time being, I have decided to help myself by compiling a small list of JQuery methods I HAVE USED SO FAR in different scenarios in order to commit it to my memory. This list will be updated with more methods in future as I use them.

  • Checkbox list has at least one item CHECKED (.length())
    example:
    if ($("div.container input:checked").length == 0)

  • CHECK/UNCHECK a Checkbox (.attr(name,value) / .removeAttr(name))
    example:
    if ($("input:checkbox").attr("checked") == true)
    $("input:checkbox").removeAttr("checked");
    else
    $("input:checkbox").attr("checked", "checked");

  • Dropdown list has a SELECTED item (.val())
    example:
    if ($("div.container select.dropdownlist").val() != -1)

  • VALUE of the Selected Checkbox (.attr())
    example:
    $("div.container input:checked").attr("value"); 

  • TEXT between <SPAN> and </SPAN> (html())
    example:
    $("div.container input:checked").find("span").html();

  • Setting the VALUE of a Textbox or a Hidden field (.val(value))
    example:
    $("div.container").siblings("#<%=hSelectedItem.ClientId%>").val(selectedVal);

  • Getting a STYLE property from first matched element (.css())
    example:
    if ($(this).siblings('.container).css("display") == 'none')) 

  • Animating the element OPACITY  (.fadeIn() / .fadeOut())
    examples:
    $(this).siblings('.itemlist').fadeIn(200);     
    $(this).siblings('.itemlist').fadeOut(200);

  • Switching between EXPAND and COLLAPSE images (.attr(name,value))
    example:
    $(this).children("img").attr("src", '<%=ImagePath%>Collapse.png');  
    $(this).children("img").attr("src", '<%=ImagePath%>Expand.png');

  • Changing the CSS CLASS NAME (.addClass(name))
    example:
    $(this).addClass("selected");

  • Creating the <OPTGROUP>s in an ASP.NET Dropdown list (.wrapAll())
    I did I blog post here about it a while ago where I have shown how <OPTGROUP>s can be created in an ASP.NET Dropdown list using just two lines of JQuery code.
    example:
    $("select.dropdownlist option[@type='1']").wrapAll('<optgroup label="Level1">'); 
    $("select.dropdownlist option[@type='2']").wrapAll('<optgroup label="Level2">');

  • Getting a COMMA SEPERATED LIST of VALUES of selected Checkboxes (.SerializeArray())
    The below small function makes use of JQuery .SerializeArray() method which returns form elements as an array of name/value pair. Each element’s value will then be pushed into another array and returned as a comma separated string.
    function GetSelectedApplicants()     
    {
    var fields = $("tr td input:checkbox:checked").serializeArray();
    $.each(fields, function(i, field)
    {
    selectedApplicants.push(field.value);
    });
    return selectedApplicants.join(',');
    }

  • Creating a DYNAMIC TOOLTIP containing the data from ASP.NET web server. (.ajax())
    I wanted to create a fancy dynamic tooltip like the one on LinkedIN® and Google Dictionary Lookup in Chrome. I ended up using JQuery .ajax() method which is calling ASP.NET server-side function asynchronously and after retrieving the data populating the tooltip container with HTML elements around the data.
    function GetItemList(item, appID) 
    {
    $.ajax({
    type: "POST",
    url: "ListApplicants.aspx/GetFolderList",
    data: "{id: " + appID + "}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg)
    {
    //hiding the loading bar once the resluts has been retrived.
    item.parent().children(".loadingbar").css("display", "none");
    item.parent().append(
    '<div class="toolTipWrapper">'
            + '<div class="closex" onclick="closex();">[x]</div>'
                    + msg.d
            + '<div class="arrowContainer">'
            + '<div class="arrowInner"></div>'
        + '<div class="arrowOuter"></div>'
    + '</div>'
    + '</div>'
    )
    }
    });
    }

  • Clearing the TEXT field on focus (.focus())
    Sometimes we need to display a default text in the textbox like “Click here to search” or “email address” to inform the user what needs to go in the textbox. The below snippet makes it easier for us to clear the text as soon as the user clicks on the textbox to type something.
    $("input.text").focus( function() {     
            if ( $(this).val() == '(email address)' || $(this).val() == 'Site Search...' )
            $(this).val('');                
    } );

  • Selecting an element which does NOT have a particular stylesheet. (:not())
    example:
    $("div.container div p:not(.quote)").css('display', 'none');

  • Appending the content of an element to the end of another element (.append())
    example:
    $("td.column").append($("div.row").contents());

Honestly, I have no intension to write another JQuery documentation, but at times it makes a lot of sense to have everything we have used so far in one place, specially if it is just one group of things being repeated again and again. The ultimate goal is to scribble down the way I have used JQuery methods with web/HTML controls.


HTH,

0 comments:

Post a Comment