Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

215
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda