Tuesday, May 11, 2010

jQuery gotchas

1. Playing with checkboxes:
To get all the checked checkboxes from a group use :
$("input.selectArticleCheckBox:checked");

2. To hide multiple elements in a screen with the same name use class instead of id:
$('tr.filterSection').show();
This shows all elements with class filterSection in a tr

3. Iterating through an array:
       $.each(
                    articles,
                    function( intIndex, obj ){                 
                        alert(obj.value);
                    }
         );

4. Check if element is visible: $('.classMessage').is(":visible")

5. Email validation using regex:
var regexEmail= /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z0-9]{2,4})$/;                          
if(!regexEmail.test(currentFieldValue)) { }

6. Manipulating select fields
$('#selectList').val();$('#selectList :selected').text();

7. Debugging jquery on stupid IE
//global catch all
function
handleError(e)
{
alert(’An error has occurred!\n’+e);
return true;
}
window.onerror = handleError;
Use stacktrace.js as a life saviour : stactrace.js
  Nice link here
  More

8. CORS - cross site ajax call using jquery.
Browsers restrict from making cross site calls. Alternative is to use JSONP (JSON with padding)
The web server hosting the JSON, should wrap the json with  the function name which needs to be implemented in the javascript/jquery code. Also the jquery should send
jsoncallback=? parameter. Also older jquery version doesnt support .ajax based jsonp.

var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, null)
.done(function( data ) {
alert("gotdata");
});
*update : the above didnt work, so tried with $.ajax() by passing jsonCallBack: "functionName"

9. show()/hide() in jquery is too slow as it does some data caching. also setting $().css("display","none") is slow.  Hence used CSS based hiding :
       $('tr.tableStyleRow').addClass("rowShowClass");
        $('tr.tableStyleRow').removeClass("rowHideClass");

.rowHideClass{
    visibility:hidden !important;;
    display:none !important;;
}
.rowShowClass{
    visibility:visible !important;;
    display:block !important;;
}



Ref:  Jquery cheat sheet :
Build your own jquery plugin tutorial
spring mvc with jquery ajax
restful spring mvc

No comments: