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

208
Views
Javascript selectors: reference selected item in child function

I have a form with ~50 inputs. I've initialized them all with a single class-selector

<input class="common-class" id="firstname" value="Some data">
<input class="common-class" id="lastname" value="Some data">

I have an arbitrary plugin (redactor) that will perform actions on the contents. I need to know which input was touched.

function arbitraryPluginFunction(input) {
    /*Plugin doing whatever it has to do */
    input.callback();
}

$(document).ready(function() {

    $(".common-class").arbitraryPluginFunction({
        initsetting1: "sample",
        initsetting2: "sample",
        callback: function() {
            console.log("You changed : " + $(this).attr("id"));
        },
    });

});

Note the error in my sample because $(this).attr() refers to the object being passed into the plugin. I have an inelegant workaround using $.each, but wondering if there's some proper way.

*** Edit *** Here's something closer to the actual call. I removed redactor from my question to simplyfy

$(document).ready(function() {

  $(".common-class").redactor({
    changeCallback: function() {
      console.log("You changed : " + $(this).attr("id"));
    });
  });

});

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

0

Unless I'm missing something, you can pass a selector to a jquery function and it will apply that function to all of the matching elements.

Then you create your funtion like $.fn.redactor and in the function $(this) will correspond to the selected element.

$(document).ready(function() {

$.fn.redactor = function(p){
   $(this).on("input",function(){
      p.changeCallback($(this).attr("id"));
   });
}

  $(".common-class").redactor({
    changeCallback: function(id) {
      console.log("You changed : " + id);
    }
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="common-class" id="firstname" value="Some data">
<input class="common-class" id="lastname" value="Some data">

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!