Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery & Objects, trying to make a lightweight widget

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?

like image 396
jason saldo Avatar asked Sep 07 '08 07:09

jason saldo


People also ask

What is jQuery used for?

jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.

Is jQuery the same as JavaScript?

The main difference among the three is that JavaScript is client-side, i.e., in the browser scripting language, whereas jQuery is a library (or framework) built with JavaScript.

Which is better js or jQuery?

Though JavaScript is the basic language from which jQuery has evolved, jQuery makes event handling, DOM manipulation, Ajax calls much easier than JavaScript. jQuery also allows us to add animated effects on our web page which takes a lot of pain and lines of code with JavaScript.

Is jQuery still used in 2021?

6 Reasons Why We Still Use jQuery in 2021. jQuery has been around for over 10 years, which is a long time for a code library. It's still one of the most popular JavaScript libraries in web development. We love jQuery here at Atypic and still utilize it in our projects.


1 Answers

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.

like image 81
Łukasz Avatar answered Oct 10 '22 01:10

Łukasz