Chris Chris - 2 months ago 5
CSS Question

How to create multiple jquery functions with one function?

I have the below jquery functions which you can find in this code pen that I would like to simplify.

I'd like to write the below javascript more concisely by writing a function that creates all the below functions, since the only difference are the following strings: name1, name2, name3, etc.

Javascript

$('#name1').on('click', function(){
document.getElementById("name1").innerHTML = "name1";
});
$('#name2').on('click', function(){
document.getElementById("name2").innerHTML = "name2";
});
$('#name3').on('click', function(){
document.getElementById("name3").innerHTML = "name3";
});
$('#name4').on('click', function(){
document.getElementById("name4").innerHTML = "name4";
});
$('#name5').on('click', function(){
document.getElementById("name5").innerHTML = "name5";
});
$('#name6').on('click', function(){
document.getElementById("name6").innerHTML = "name6";
});


HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button type="button" id="name1">NAME</button>
<button type="button" id="name2">NAME</button>
<button type="button" id="name3">NAME</button>
<button type="button" id="name4">NAME</button>
<button type="button" id="name5">NAME</button>
<button type="button" id="name6">NAME</button>

Answer

I think this is the simplest solution:

$('button').on('click', function() {
  $(this).html($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="name1">NAME</button>
<button type="button" id="name2">NAME</button>
<button type="button" id="name3">NAME</button>
<button type="button" id="name4">NAME</button>
<button type="button" id="name5">NAME</button>
<button type="button" id="name6">NAME</button>

If you want this to work on specific buttons you can use $('#name1,#name2,#name3...').on.
If they all have specific class you can use $('.specific-class').on.
If they all exists inside some specific element you can use $('div#id1 button').on
And so on...

Comments