Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

what is wrong with this jQuery function?

I had this jQuery event handler code and i wanted to convert it into a function

$("#activate-user").click(function() {
    var userId = [];
    $(':checkbox:checked').each(function(i) {
        userId[i] = $(this).val();
    });
    if(userId.length == 0) {
        //If userId is empty
    } else {
        $.ajax({
            type: 'POST',
            url:  'process.php',
            data: 'option=activate&userId='+userId,
            success: function(msg){
                if(msg == 0) {
                    //If cannot process the query.
                } else {
                    //If query is processed.
                    location.reload(true);
                }
            }
        });
    }   
});

$("#block-user").click(function() {
    var userId = [];
    $(':checkbox:checked').each(function(i) {
        userId[i] = $(this).val();
    });
    if(userId.length == 0) {
        //If userId is empty
    } else {
        $.ajax({
            type: 'POST',
            url:  'process.php',
            data: 'option=block&userId='+userId,
            success: function(msg){
                if(msg == 0) {
                    //If cannot process the query.
                } else {
                    //If query is processed.
                    location.reload(true);
                }
            }
        });
    }
});

the only difference between this two Event handlers are, a value i.e option=

  1. data: 'option=activate&userId='+userId
  2. data: 'option=block&userId='+userId

i want this to convert it into jQuery function for which i tried doing this way which does not work at all,

(function ($) {
jQuery.fn.userOperation = function(opString) {
    this.click(function() {
        var userId = [];
        $(':checkbox:checked').each(function(i){
            userId[i] = $(this).val();
        });
        if(userId.length === 0) {
            //If userId is empty.
        } else {
            $.ajax({
                type: 'POST',
                url:  'process.php',
                data: 'option='+opString+'&userId='+userId,
                success: function(msg){
                    if(msg == 0) {
                        //If cannot process the query.
                    } else {
                        //If query is processed.
                        location.reload(true);
                    }
                }
            });
        }
    });
}
}(jQuery));

jQuery Function Call :

$('#activate-user').userOperation(function() {
    return 'block';
});

this does not seems to work, as i am not passing the argument correctly to the function, as i am a novice in jQuery, i am not sure how do i do this. where am i going wrong? which is the correct and feasible way of passing the argument into the jQuery function?

thank you..

Upvotes: 0

Views: 128

Answers (3)

Brad Christie
Brad Christie

Reputation: 101604

My Bid:

// use an anonymous function to we can still reference the short version
//  of jQuery ($) even in situations where $.noConflict() was applied.
(function($){

    // extending the $.fn is saying "We want to add a function as part of jQuery"
    $.fn.extend({

        // here's the new function we're adding:
        // $(selector).userOperation(action);
        userOperation: function(action){

            // return an each iterator so we can bind to multiple selectors
            // and so we can chain (e.g. $('#foo,#bar).userOperation('delete').show();)
            return this.each(function(i,e){

                // grab the current element and bind to its click event
                $(e).click(function(){

                    // go through the checked boxes and find userIds we're working on
                    // map() makes this easy because it will go through each found item,
                    // process it (in this case return only it's value) then return those
                    // results as an object. Then, we call toArray() so all we have is an
                    // array full of those found values.
                    var userId = $(':checkbox:checked').map(function(i,el){
                      return $(el).val());
                    }).toArray();

                    // check if we have userId entries
                    if (userId.length > 0){

                        // we have entries, fire off the AJAX call
                        $.ajax({
                            type: 'POST',
                            url: 'resources/library/models/users/process.php',
                            data: 'option='+action+'&userId='+userId.join(','),
                            success: function(msg){
                                if (msg == 0){
                                    // cannot process
                                }else{
                                    location.reload(true);
                                }
                            }
                        });
                    }else{
                        // userId array is empty
                    }

                    // block action, in case we bind click to anchors
                    e.preventDefault();
                });
            });
        }
    });

})(jQuery);

// this is how we would attach it to various elements:
$('#block').userOperation('block');
$('#activate').userOperation('activate');

Also allows you to bind to multiple selectors, use chaining, etc. I also explicitly call a join on the userId array instead of allowing javascript to default to casting an array to string. This appears more readable for anyone going through the code, IMHO.

Upvotes: 2

Jason Kaczmarsky
Jason Kaczmarsky

Reputation: 1686

$('#activate-user').userOperation("block");

The data parameter needs a sting and your argument makes the data parameter, so pass it the action you want to take, IE a string.

Upvotes: 1

FishBasketGordo
FishBasketGordo

Reputation: 23142

For one, you're passing a function to userOperation, but it expects a string.

Instead of this:

$('#activate-user').userOperation(function() {
    return 'block';
});

Do this:

$('#activate-user').userOperation('block');

Upvotes: 1

Related Questions