Shrink
Shrink

Reputation: 95

jQuery function optimization

Is there a way to make this faster?

This function manages some dynamic form elements.

 function HideAllDivs(parentDiv) {
        var divs = $('#' + parentDiv + ' div'), divsLength = divs.length;   
        for (var a = 0; a < divsLength; a++) {
            var obj = $('#' + divs[a].id);
            obj.find('input[type=radio]:checked').removeProp('checked');
            obj.find('input[type=checkbox]:checked').removeProp('checked');
            obj.find('input[type=text]').val('');
            obj.find('select').val('');
            obj.find('input[type=radio]').each(function () { $(this).removeClass('selectedCtrl');   });
            obj.hide(1);                           
        }    
    }

Thanks, David

Upvotes: 2

Views: 97

Answers (3)

simey.me
simey.me

Reputation: 2207

I thought this should be slightly faster...

function HideAllDivs(parentDiv) {

  var $divs = $('#' + parentDiv + ' div');

  $divs
    .find('input[type=text],select').val('').end()
    .find(':checked').removeProp('checked').end()
    .find('.selectedCtrl[type=radio]').removeClass('selectedCtrl').end()
    .hide(1);
}

Performance tests below
* Edit: Fail, I didn't actually run the tests -_-; fixed.*
http://jsperf.com/hiding-divs-19362135

Upvotes: 0

techfoobar
techfoobar

Reputation: 66663

You can speed it up (slightly) by using..

function HideAllDivs(parentDiv) {
    $('#' + parentDiv + ' div')
        .hide()
        .find('input, select')
            .removeProp(':checked') // will be ignored where not applicable
            .removeClass('selectedCtrl') // will be ignored where not applicable
            .filter('input[type="text"], select').val('');
}

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388316

There is no need to use a loop and you can improve the 2 operations using radio buttons

function HideAllDivs(parentDiv) {
    var divs = $('#' + parentDiv + ' div');

    var radios = divs.find('input[type=radio]')
    radios.filter(':checked').removeProp('checked');
    radios.find('.selectedCtrl').removeClass('selectedCtrl');

    divs.find('input[type=checkbox]:checked').removeProp('checked');
    divs.find('input[type=text], select').val('');
    divs.hide(1);
}

Upvotes: 1

Related Questions