views:

279

answers:

2

Trying to make a make generic select "control" that I can dynamically add elements to, but I am having trouble getting functions to work right.

This is what I started with.

$select = $("<select></select>");
$select.addOption = function(value,text){
$(this).append($("<option></option>").val(value).text(text));
  };

This worked fine alone but anytime $select is .clone(true)'ed the addOption() function is lost.

This is my object approach but still the function does not work.

function $selectX() {
        return $("<select></select>");
        }

$selectX.prototype.addOption() = function(value,text){
         $(this).append($("<option></option>").val(value).text(text));
      };

Hack solution is to add the function manually after creation:

$nameSelect= new $selectX;
$nameSelect.addOption = function(value,text){
     $(this).append($("<option></option>").val(value).text(text));
 };

Am I barking up the wrong tree?

+6  A: 

To add new method to jQuery You need to use jQuery.fn.methodName attribute, so in this case it will be:

jQuery.fn.addOption = function (value, text) {
    jQuery(this).append(jQuery('<option></option>').val(value).text(text));
};

But keep in mind that this addOption will be accessible from result of any $() call.

Łukasz
A: 

In the link below, you will find the sample code for a plugin which will create widgets automatically. You may customize it as per your need

http://sites.google.com/site/spyderhoodcommunity/tech-stuff/jquerydashboardwidgetplugin

Kartik Sehgal