doovers
doovers

Reputation: 8675

More efficient way to write jQuery function

Is there a better way to write this function? I'm pretty sure I only need one function here but I don't know how to write it!

(function(jQuery){
    jQuery.fn.codeexists = function(code) {
        var codeexist = false;
        jQuery('#fault-list-tbl tbody tr').each(function (i, row) {
            var id = jQuery(this).find('.fault-tbl-code').html();
            if (id == code) {
                codeexist = true;
            };
        });
        if (codeexist) {
            return true;
        } else {
            return false;
        };
    }; 
})(jQuery);

Upvotes: 1

Views: 152

Answers (2)

tckmn
tckmn

Reputation: 59283

This could be much simpler:

jQuery.fn.codeexists = function(code) {
    return jQuery('#fault-list-tbl tbody tr .fault-tbl-code').filter(function() {
        return this.html() === code;
    }).length > 0;
};

filter filters the elements down to only the ones which have an html of code, and length is how many elements. Therefore, if there's more than 0 (length > 0) elements which have code as their html, it returns true.

Upvotes: 5

megawac
megawac

Reputation: 11353

You can also write it like this:

(function($){
    $.fn.codeexists = function(code) {
        var codeexist = false;
        $('#fault-list-tbl tbody tr .fault-tbl-code').html(function (i, id) {
            if (id == code) {
                codeexist = true;
            };
        });
        return codeexist;
    }; 
})(jQuery);

Upvotes: 2

Related Questions