about jQuery find

if an element doesn’t exist, jQuery’s find method will not return undefined, instead it will create a new object and return it. So if you want to detect if an element exists or not, then you should use the length property. For example:

if (0 == $(‘div’).find(‘ul’).length) { // if div doesn’t contain any ul element

// do whatever

}

Advertisements

Example of using mockjax and qunit to test ajax call

asyncTest(“Test successful getTradePeriod Ajax call should fill out trade period dropdown list”, function(){
$(‘<select id=”tradePeriod”></select>’)
.appendTo(“#qunit-fixture”);

$.mockjax({
url: ‘/DATData/getTradePeriod’
,type: ‘POST’
,responseTime: 100
,dataType: ‘xml’
,responseXML:'<tradePeriods>’
+   ‘<data><fromDate>2014-10-01</fromDate><toDate>2014-10-08</toDate></data>’
+   ‘<data><fromDate>2014-10-09</fromDate><toDate>2014-10-16</toDate></data>’
+ ‘</tradePeriods>’
});

equal($(‘#tradePeriod option’).size(), 0);

loadTradePeriod();

setTimeout(function() {
equal($(‘#tradePeriod option’).size(), 2);
start();
}, 200);
});

Tip: 1. use asyncTest; 2. put expected wait time (longer than response time) in setTimeout function.

Example of a jQuery plugin to animate table rows

From: http://stackoverflow.com/questions/467336/jquery-how-to-use-slidedown-or-show-function-on-a-table-row

(function($) {
var sR = {
    defaults: {
        slideSpeed: 400,
        easing: false,
        callback: false     
    },
    thisCallArgs: {
        slideSpeed: 400,
        easing: false,
        callback: false
    },
    methods: {
        up: function (arg1,arg2,arg3) {
            if(typeof arg1 == 'object') {
                for(p in arg1) {
                    sR.thisCallArgs.eval(p) = arg1[p];
                }
            }else if(typeof arg1 != 'undefined' && (typeof arg1 == 'number' || arg1 == 'slow' || arg1 == 'fast')) {
                sR.thisCallArgs.slideSpeed = arg1;
            }else{
                sR.thisCallArgs.slideSpeed = sR.defaults.slideSpeed;
            }

            if(typeof arg2 == 'string'){
                sR.thisCallArgs.easing = arg2;
            }else if(typeof arg2 == 'function'){
                sR.thisCallArgs.callback = arg2;
            }else if(typeof arg2 == 'undefined') {
                sR.thisCallArgs.easing = sR.defaults.easing;    
            }
            if(typeof arg3 == 'function') {
                sR.thisCallArgs.callback = arg3;
            }else if(typeof arg3 == 'undefined' && typeof arg2 != 'function'){
                sR.thisCallArgs.callback = sR.defaults.callback;    
            }
            var $cells = $(this).find('td');
            $cells.wrapInner('<div class="slideRowUp" />');
            var currentPadding = $cells.css('padding');
            $cellContentWrappers = $(this).find('.slideRowUp');
            $cellContentWrappers.slideUp(sR.thisCallArgs.slideSpeed,sR.thisCallArgs.easing).parent().animate({
                                                                                                                paddingTop: '0px',
                                                                                                                paddingBottom: '0px'},{
                                                                                                                complete: function () {
                                                                                                                    $(this).children('.slideRowUp').replaceWith($(this).children('.slideRowUp').contents());
                                                                                                                    $(this).parent().css({'display':'none'});
                                                                                                                    $(this).css({'padding': currentPadding});
                                                                                                                }});
            var wait = setInterval(function () {
                if($cellContentWrappers.is(':animated') === false) {
                    clearInterval(wait);
                    if(typeof sR.thisCallArgs.callback == 'function') {
                        sR.thisCallArgs.callback.call(this);
                    }
                }
            }, 100);                                                                                                    
            return $(this);
        },
        down: function (arg1,arg2,arg3) {
            if(typeof arg1 == 'object') {
                for(p in arg1) {
                    sR.thisCallArgs.eval(p) = arg1[p];
                }
            }else if(typeof arg1 != 'undefined' && (typeof arg1 == 'number' || arg1 == 'slow' || arg1 == 'fast')) {
                sR.thisCallArgs.slideSpeed = arg1;
            }else{
                sR.thisCallArgs.slideSpeed = sR.defaults.slideSpeed;
            }

            if(typeof arg2 == 'string'){
                sR.thisCallArgs.easing = arg2;
            }else if(typeof arg2 == 'function'){
                sR.thisCallArgs.callback = arg2;
            }else if(typeof arg2 == 'undefined') {
                sR.thisCallArgs.easing = sR.defaults.easing;    
            }
            if(typeof arg3 == 'function') {
                sR.thisCallArgs.callback = arg3;
            }else if(typeof arg3 == 'undefined' && typeof arg2 != 'function'){
                sR.thisCallArgs.callback = sR.defaults.callback;    
            }
            var $cells = $(this).find('td');
            $cells.wrapInner('<div class="slideRowDown" style="display:none;" />');
            $cellContentWrappers = $cells.find('.slideRowDown');
            $(this).show();
            $cellContentWrappers.slideDown(sR.thisCallArgs.slideSpeed, sR.thisCallArgs.easing, function() { $(this).replaceWith( $(this).contents()); });

            var wait = setInterval(function () {
                if($cellContentWrappers.is(':animated') === false) {
                    clearInterval(wait);
                    if(typeof sR.thisCallArgs.callback == 'function') {
                        sR.thisCallArgs.callback.call(this);
                    }
                }
            }, 100);
            return $(this);
        }
    }
};

$.fn.slideRow = function(method,arg1,arg2,arg3) {
    if(typeof method != 'undefined') {
        if(sR.methods[method]) {
            return sR.methods[method].apply(this, Array.prototype.slice.call(arguments,1));
        }
    }
};
})(jQuery);

Basic Usage:

$('#row_id').slideRow('down');
$('#row_id').slideRow('up');

Pass slide options as individual arguments:

$('#row_id').slideRow('down', 500); //slide speed
$('#row_id').slideRow('down', 500, function() { alert('Row available'); }); // slide speed and callback function
$('#row_id').slideRow('down', 500, 'linear', function() { alert('Row available'); }); slide speed, easing option and callback function
$('#row_id').slideRow('down', {slideSpeed: 500, easing: 'linear', callback: function() { alert('Row available');} }); //options passed as object

Basically, for the slide down animation, the plug-in wraps the contents of the cells in DIVs, animates those, then removes them, and vice versa for the slide up (with some extra steps to get rid of the cell padding). It also returns the object you called it on, so you can chain methods like so:

$('#row_id').slideRow('down').css({'font-color':'#F00'}); //make the text in the row red

Explanation on animating table rows

from: http://blog.slaks.net/2010/12/animating-table-rows-with-jquery.html

jQuery contains a powerful and flexible animation engine.  However, it has some limitations, primarily due to underlying limitations of CSS-based layout

For example, there is no simple way to slideUp() a table row (<tr> element).  The slideUp animation will animate the element’s height to zero.  However, a table row is always tall enough to show its elements, so the animation cannot actually shrink the element.

To work around this, we can wrap the contents of each cell in a <div> element, then slideUp() the <div> elements.  Doing this in the HTML would create ugly and non-semantic markup, so we can do it in jQuery instead.

For example: Demo

$('tr')
    .children('td, th')
    .animate({ padding: 0 })
    .wrapInner('<div />')
    .children()
    .slideUp(function() { $(this).closest('tr').remove(); });

Explanation:

  1. Get all of the cells in the row
  2. Animate away any padding in the cells
  3. Wrap all of the contents of each cell in one <div> element for each cell (calling wrapInner())
  4. Select the new <div> elements
  5. Slide up the <div>s, and remove the rows when finished.

If you don’t remove the rows, their borders will still be visible.  Therefore, if you want the rows to stay after the animation, call hide() instead of remove().

jQuery Soap Ajax Request Example

var userName=’myUserName’;

var password=’myPassword’;

var soapenvHeader =
‘<soapenv:Header><wsse:Security xmlns:wsse=”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd”&#8216; +
‘ xmlns:wsu=”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd”>&#8217; +
‘<wsse:UsernameToken wsu:Id=”UsernameToken-6″> ‘+
‘<wsse:Username>’+userName+'</wsse:Username>’+
‘<wsse:Password Type=”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText”>’+password+'</wsse:Password&gt; ‘ +
‘<wsse:Nonce EncodingType=”http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary”>sNuKHy0WlAszlbmjYz7i/g==</wsse:Nonce><wsu:Created>2014-10-02T17:15:57.362Z</wsu:Created></wsse:UsernameToken></wsse:Security></soapenv:Header>&#8217;;

function getRequestBody(zipcode, soapAction) {
// build SOAP request
var soadpenvBody =
‘<soapenv:Body>’+
‘<ajax:’+soapAction + ‘>’ +
‘<zipcode>’ + zipcode + ‘</zipcode>’+
‘</ajax:’+soapAction+’>’ +
‘</soapenv:Body>’;

var soapenvEnvelope =
getSoapEnvelop(soapenvHeader, soadpenvBody);
return soapenvEnvelope;
}

function getSoapEnvelop(soapenvHeader, soadpenvBody) {
var ret =  ‘<?xml version=”1.0″ encoding=”utf-8″?>’ +
‘<soapenv:Envelope ‘ +
‘xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; ‘ +
‘xmlns:ajax=”http://www.tibco.com/bs3.0/_BexlQEo4EeSHK8i-eh2cKg/AjaxServicesProcess&#8221; ‘ +
‘xmlns:xsd=”http://www.w3.org/2001/XMLSchema&#8221; ‘ +
‘xmlns:soapenv=”http://schemas.xmlsoap.org/soap/envelope/”>&#8217; +
soapenvHeader +
soadpenvBody +
‘</soapenv:Envelope>’;
return ret;
}

function sendAjaxRequest(urlInput,soapActionInput,requestBody, successCallback, errorCallback) {
$.ajax({
url: urlInput
,data: requestBody
,type: “POST”
,dataType: “xml”
,headers: {
SOAPAction: soapActionInput
}
,contentType: “text/xml”
,success:successCallback
,error: errorCallback
});
}