Consider the following Event based example.
$(function() {
function myFunction(event) {
var $el = $(event.target);
$el.prop("disabled", true);
console.log("Disabled " + $el.attr("id"));
}
$("button").click(myFunction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button-1">Button 1</button>
<button id="button-2">Button 2</button>
<button id="button-3">Button 3</button>
<button id="button-4">Button 4</button>
This uses the event
to select the target. So event.target
is the target element and using $(event.target)
creates it as a jQuery Object.
If you want to pass in a String, you can do that. It might look like this.
$(function() {
function myFunction(elemId) {
var $el;
if (typeof elemId == 'string') {
$el = $("#" + elemId);
} else {
$el = $(elemId);
}
$el.prop("disabled", true);
console.log("Disabled " + $el.attr("id"));
}
$("button").click(function() {
myFunction($(this).attr("id"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button-1">Button 1</button>
<button id="button-2">Button 2</button>
<button id="button-3">Button 3</button>
<button id="button-4">Button 4</button>