Tips for sending a unique button ID to a jQuery click function

Within a table row of a dynamically generated table, I have multiple buttons each with its own functionality. My goal is to figure out how to pass the specific button ID to the onclick event of that table row when one of these buttons is clicked.

 $('#demotbl').DataTable( {
      "aaData": data,
      "aoColumns": [
          { "sTitle": "PrescriptionId" },
          { "sTitle": "PatientNumber" },
          { "sTitle": "PatientName" },
          { "sTitle": "Address" },
          { "sTitle": "PhoneNumber" },
          { "sTitle": "Prescription" },
          { "sTitle": "Date" },
          {
              "targets": -1,
              "data": null,
              "defaultContent": "<input type='submit' id ='btn2' name='btn2' value='view' />"
          },
           {
              "targets": -2,
              "data": null,
              "defaultContent": "<input type='file' class='cloudinary-fileupload' data-cloudinary-field= 'image_id' />"
          },
           {
              "targets": -3,
              "data": null,
              "defaultContent": "<input type='submit' id='btn' name='btn' value="btn" />"
          }




      ]

    })


                    var table = $('#demotbl').DataTable();



     $('#demotbl tbody').on( 'click', 'button', function (e) {
        e.preventDefault();
        console.log('selected')
        var tr = $(this).closest('tr');
        var rows = table.row(tr);

        var info = rows.data();
        var dat = [info];
        var patient_info = info[1];

        console.log( "patientinfo",info);
      // demoFromHTML(dat)






    } );

How can I effectively pass button IDs within the above code snippet, especially when dealing with the onclick event in jQuery?

Answer №1

  1. Assign the same class name to each button element
  2. Trigger the click event using the class name
  3. Retrieve the id using .attr()

For example:

<input type='submit' class='btn' id ='btn1' value='view'/>
<input type='submit' class='btn' id ='btn2' value='view'/>

and

$('.btn').click(function(){
    $(this).attr('id');
})

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

Improving efficiency of basic image carousel in Angular 8

In my Angular 8 app, I am developing a basic carousel without relying on external libraries like jQuery or NgB. Instead, I opted to use pure JS for the task. However, the code seems quite cumbersome and I believe there must be a more efficient way to achie ...

Persistent hover state remains on buttons following a click event

In my current project, I am dealing with a form that has two distinct states: editing and visible. When the user clicks on an icon to edit the form, two buttons appear at the bottom - one for saving changes and one for canceling. Upon clicking either of th ...

Modify a class attribute within a function

I need to modify the this.bar property within my class when a click event occurs. The issue is that the context of this inside the click function is different from the this of the class. export class Chart { constructor() { this.bar; } showC ...

Is the presence of the selenium webdriver being registered?

Is there a method to detect if a website can tell I am using a bot while running Selenium WebDriver in Python or Puppeteer in JavaScript? Are there any resources that indicate whether a bot test would be failed, such as Cloudflare or Captcha? Appreciate a ...

Using AJAX to dynamically update content via HTTP requests

Why do I keep seeing "loading..." instead of the content from data.php? xmlhttp = new XMLHttpRequest(); function fetchData () { xmlhttp.onreadystatechange = function () { if(xmlhttp.readyState = 4 && xmlhttp.status == 20 ...

I'm puzzled as to why this code snippet consistently produces a range of 50 to 100 repeated values. This piece of code is crucial for altering the behavior of a function based on a specific

Below is a snippet of my React code aiming to alter the functionality of a function based on a specific window width: const [windowWidth, setWindowWidth] = useState({ winWidth: 0 }); useEffect(() => { window.addEventListener('resize', ( ...

Is there a way to save and print output in a Laravel store function within a controller?

I have a button that saves and prints data. Currently, I have the saving functionality implemented in the store() function, but I am struggling with making it trigger a print dialog for the passed data. Below are the buttons: <button type="button& ...

Utilize HTML or JavaScript to make a POST request with Express

Recently, I decided to dip my toes into the world of back-end development using express for the first time. I came across a situation where I needed to make a POST request from an html/js file, and initially used Jquery to accomplish this task. However, I ...

Trouble Arising from Making a POST Request to Spotify's API

I am currently developing a web application that allows users to search the Spotify Library, add songs to playlists, and then save those playlists to their Spotify Accounts. Almost everything is functioning correctly except for the saving of playlists thro ...

How can I retrieve a specific key from a nested array while using ng-repeat to iterate through it

I have successfully created a code snippet that retrieves JSON data and displays it in HTML using AngularJS. <div class="activity" ng-app="stream" ng-controller="streamCtrl"> <ul ng-repeat="x in myData"> <p class="au ...

jq mobile link triggering unexpected scroll to page bottom

Seeking assistance from the community. I am currently working on an app in PhoneGap with jQuery Mobile and facing a problem whereby when there is a hyperlink in the text below the 'fold' of the iPhone screen, the page automatically jumps to the b ...

Click to open the file browser by using the onclick event in Material-table actions

Currently, I am working with a Material table component from "@material-table/core" My goal is to implement an action that enables users to upload a file within this table. I am facing some challenges on how to trigger the file browser when the ...

Confused about having to use window.variableName in my code and not understanding the reason

Working on a web app with JS, Angular, and Meteor that integrates the Youtube API has been quite challenging. In one of my controllers, I initialized the youtube player object in the constructor following the necessary steps outlined by the Youtube API. Ho ...

filtering the properties of mongoose documents

I have created a schema as shown below: var UserSchema = new Schema({ firstName: { type: String, required: true }, lastName: { type: String, required: true }, email: { type: String, required: true }, location: { type: String, required: true }, p ...

Incorporating DefinitelyTyped files into an Angular 2 project: A step-by-step guide

I am currently developing an application using angular 2 and node.js. My current task involves installing typings for the project. In the past, when starting the server and activating the TypeScript compiler, I would encounter a log with various errors rel ...

Manipulating web elements by traversing through selected identifiers in LocalStorage and eliminating them from the document layout

I have a multitude of localStorage keys, including ones labeled Cart, Viewed, and Trash. There are two aspects to my query: 1) What is the most efficient way to loop through the item IDs in localStorage and add a class or data attribute to the correspond ...

Is it possible for the Redux inside a React component from npm to clash with the Redux in the container?

I am looking to bundle a React component with npm and incorporate Redux to handle state within the component. If another React project imports my component, will it cause conflicts with the Redux instance of that project? For example: The component code ...

Is it conceivable that Jquery is failing to load for an Ajax request?

I have been experiencing an issue with my jQuery code not working within Ajax requests. The jQuery plugin I am using is FancyBox which can be found at . When calling the FancyBox plugin directly, everything works perfectly and multiple links load the plugi ...

Utilizing JSON and CodeIgniter within HTML elements

I am interested in creating a private chatroom using CodeIgniter and JSON format. I want the JSON data retrieved to be displayed in a list structure like <ul><li>messageinJSON</li></ul>. This formatting will allow me to customize th ...

Is there a way to run /_next/static/xxx.js using a script tag?

I have customized my next.config file (webpack) to generate a static JavaScript file (.next/static/loader.js). The original loader.js is an Immediately Invoked Function Expression (IIFE): (function stickerLoader(){ alert('Hello'); // ... so ...