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"));
});
});
});
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">