views:

19

answers:

1

Hi all,

I have the following two functions and i need help moving these into an external file.

 $.fn.clearSelect = function () {
        return this.each(function () {
            if (this.tagName == 'SELECT')
                this.options.length = 0;
        });
    }

    $.fn.addItems = function(data) {
        return this.each(function () {
            var list = this;
            $.each(data, function (index, itemData) {
                var option = new Option(itemData.Text, itemData.Value);

                list.add(option);
            });
        });
    }

Is there something special that i would need to do? I've attempted to do this by myself and i came up with the following, but i'm getting the an "Uncaught SyntaxError: Unexpected token )".

(function ($) {
    clearSelect = function () {
        return this.each(function () {
            if (this.tagName == 'SELECT')
                this.options.length = 0;
        });
    };

    addItems = function (data) {
        return this.each(function () {
            var list = this;
            $.each(data, function (index, itemData) {
                var option = new Option(itemData.Text, itemData.Value);
                list.add(option);
            });
        });
    };
})(jQuery);

Thanks

+1  A: 

Your initial approach should work...just make sure the file is included after jQuery itself. You can test it here.

Another option is to extend $.fn similar to your second attempt, like this:

(function($) {
  $.fn.extend({
    clearSelect: function() {
      return this.each(function() {
        if (this.tagName == 'SELECT') this.options.length = 0;
      });
    },
    addItems: function(data) {
      return this.each(function() {
        var list = this;
        $.each(data, function(index, itemData) {
          var option = new Option(itemData.Text, itemData.Value);
          list.add(option);
        });
      });
    }
  });
})(jQuery);

You can test that version here.

Nick Craver
yeah it looks like it's working on your test site. I guess there's something else wrong on my own page which is causing it to throw a new Uncaught TypeError: Object #<an Object> has no method 'clearSelect'. Thanks for your help though.
zSysop