Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top