Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
How to create a getter and setter for jquery object?

I want to add a getter and a setter for the $ object, similar to the val() function for a DOM object.

If the val is called without parameters, the getter is invoked. With one parameter, the setter is invoked.

I have tried with

$.fn.simpleSearch = function() {
    return _variable;
}

$.fn.simpleSearch = function (search) {
    _variable = search;
}

But it does not work.

Any hint?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You cannot define $.fn.simpleSearch twice. The 2nd definition will override the first.

You can set up a simple getter and setter like this:

$.fn.simpleSearch = function (search) {
    if ( typeof search != 'undefined' ) {
        _variable = search;
    }
    return _variable;
}

console.log( $(jQuery).simpleSearch() )
console.log( $(jQuery).simpleSearch('foo') )

However, this code is not complete because _variable needs to be defined somewhere. Do you intend it to be a global variable? A property of an object?

Also see How to create custom JQuery function and how to use it?

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!