Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda