Efficiently creating a multitude of jQuery functions using a single function

If you want to simplify the below jQuery functions, you can check out this code pen where they are showcased.

You can condense the JavaScript code by creating a function that handles all the functions below, with the only difference being the specific strings like name1, name2, name3, and so on.

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 №1

Here is a simple solution that I think will work:

$('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 only want this to apply to specific buttons, you can use $('#name1,#name2,#name3...').on.
If all the buttons have a specific class, you can use $('.specific-class').on.
If they are all contained within a specific element, you can use $('div#id1 button').on
And so on...

Answer №2

If you want to simplify your code and target all the buttons on the page, try using a more general selector:

$('button').on('click', function(){
    //
});

Instead of setting the "currently clicked element" to its id value, you can make it more versatile:

$('button').on('click', function(){
    this.innerText = this.id;
});

However, if targeting every button is too broad, you can still specify a list of specific id values as selectors:

$('button[id^="name"]').on('click', function(){
    this.innerText = this.id;
});

Another approach could be:

$('#name1, #name2, #name3, #name4, #name5, #name6').on('click', function(){
    this.innerText = this.id;
});

In cases where there are many elements to target, consider assigning click handlers to a parent element instead of each individual element:

$(document).on('click', '#name1, #name2, #name3, #name4, #name5, #name6', function(){
    this.innerText = this.id;
});

This method involves assigning one handler function to the document and evaluating the target button elements dynamically when the handler is executed.

Answer №3

Simplify your jQuery code in the following ways:

$('button[id^="name"]').on('click', function(){
    var id = $(this).attr("id"),
        num = id.replace("name", "");
    document.getElementById("name" + num).innerHTML = "name" + num;
});

Alternatively, you can achieve the same result using pure jQuery like this:

$('button[id^="name"]').on('click', function(){
    var button = $(this),
        id = button.attr("id");

    button.html("name" + id.replace("name", ""));
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

transmitting a JSON object to PHP with the help of jQuery

I am attempting to send the given data structure to the server using JSON: {"1":{"9":["Foto","45", "39"],"24":["Video","34", "8"]}, "2":{"45":["Camara","3", "40"],"7":["Video","96", "7"]}} Utilizing the push function in this manner: var a = {}; var b ...

Retrieve data from multiple JSON tables using a JavaScript loop

Check out this Codepen for a working example. I am relatively new to Javascript, so I may not be approaching this problem the best way. If you have any suggestions on how I could improve my approach, I would greatly appreciate it; always looking to learn ...

how to halt page loading in CodeIgniter using jQuery and AJAX for bookmark functionality

I am currently working on implementing a bookmarking feature using codeigniter, jquery, and AJAX. Below you will find the HTML form as well as the corresponding jQuery code. Current Issue: The form successfully submits data to the database The page relo ...

Unattended vuejs prototype arrays are not being monitored

During my Vue.js project, I attempted to create a global alert/notification system at the root level of the application. My approach involved pushing objects into an array and passing it to the component. In my app.vue file: <template> <div id ...

HTML5 elements for displaying search results

Similar Post: Improving search result list structure with HTML5 semantics I have retrieved a list of items from a database query. Now I need to present them to the user using HTML. This is my current approach: <ol> <li> Search Elem ...

How can we convert a group of HTML elements sharing a common attribute into an array containing their respective values?

Consider the following HTML structure: <span class="L5" letters="a"></span> <span class="L5" letters="b"></span> <span class="L5" letters="c"></span> <span class="L5" letters="d"></span> <span class="L5" ...

The context of the Nuxt.js3 plugin loses its definition

Currently, I am working on a project that involves Nuxt.js3 and supabase integration. In my plugins/supabase.server.js file (I am still unsure whether using server or client is the best approach), I want to call "supabase = createClient(~~)" from index.vu ...

Utilizing jQuery to correspond with CSS media queries

Continuing from my previous question about an automatic jQuery image slider, you can refer to it here. I have made some changes in my CSS using media queries and I am trying to incorporate them into my JavaScript code using an 'if / else if' sta ...

Retrieve the Id value from a Kendo Hierarchical grid

I have a hierarchical grid set up with a ClientDetailTemplate in the following manner. @(Html.Kendo().Grid(Model.NotesList) //Binding the grid to NotesList .Name("activityNotesGrid") .Columns(columns => { // Creating a col ...

"Can someone explain why my jQuery select function is continuously looping when

I've been struggling to understand why I keep getting multiple repeated alerts every time there is a change... $(function(){ $("#shift_name_<?php print $shift_id;?>").change(function () { $(".alertmessage").load("messages.php?ei ...

Would it be considered plagiarism to utilize a jquery plugin in a school assignment?

For my school project, I decided to incorporate a weekly schedule using a jquery plugin called FullCalendar. Do you think this could be considered plagiarism since the javascript in the plugin is doing most of the heavy lifting? ...

Using jQuery to wrap content in parentheses when a class is detected inside them

To highlight code within parentheses() when a specific class is present, a regex can be used. The code snippet below uses jQuery to achieve this: var o = jQuery(".wp-site-blocks"); o.html(o.html().replace(/\([^\)]*?\)/g, '<span clas ...

Unable to retrieve data from a textarea in order to update Mongodb using Express.js

I am currently in the process of creating a notes application using express and MongoDB. I've encountered a bug where I am unable to update the description of the notes, only the title. Below is the form that I am using to collect the data: <div cl ...

Nodemon is not auto-reloading my server even after I have updated the code

I'm having trouble with nodemon not restarting my file after I make changes to it. It says it's restarting but doesn't actually do it. I've attempted putting the nodemon command into npm start and using the -L flag, but it hasn't s ...

Tips for including an HTML table in Rmarkdown

I recently utilized the 'sjPlot' package to perform data analyses. Specifically, I used the 'sjt.df' function to generate a HTML table that provides a simple description of variables in my dataset. I then proceeded to create an Rmarkdow ...

I'm having trouble getting my JavaScript code to run, can anyone offer any advice on what

Can you provide assistance with this code? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv=" ...

Tips for preventing duplicate Java Script code within if statements

In my function, there are various statements to check the visibility of fields: isFieldVisible(node: any, field: DocumentField): boolean { if (field.tag === 'ADDR_KOMU') { let field = this.dfs_look(node.children, 'ADDR_A ...

Updating a specific child element within an array in a MongoDB collection with Mongoose:

I am completely new to working with mongodb/mongoose. Here is an example of a mongoose document that I have: const MySchema = mongoose.Schema({ name: { type: String, minLength: 5, maxlength: 100, required: true }, children: [{ nam ...

Ways to change the row height of the dropdown list according to the information in the second column?

I utilized the selectMenu jQuery widget to create a dropdown list and then incorporated it into Angular to build a reusable dropdown component. The issue I am currently dealing with is related to the height adjustment of the columns within each row of the ...

Various HTML origins

Upon examining the page source, I noticed that it contains JavaScript code: <script language="javascript" type="text/javascript"> styling += 'ul#topnav a.tabHeader5'; styling += '{'; ...