I am trying to access the id of the button that was selected, but I am unsure of how to retrieve the id from it. The method of using

I am trying to retrieve the id of a selected button for deletion purposes. However, I am unable to get the id from it using 'this.id'. Is there another method I should be using?

Below is the code where I create the button:

var deleteEmployer= document.createElement("td");

var deleteEmployerButton= document.createElement("input");
deleteEmployerButton.setAttribute("type", "submit");
deleteEmployerButton.setAttribute("value", "delete");               
deleteEmployerButton.setAttribute("id", employer.employer_id);
deleteEmployer.appendChild(deleteEmployerButton);

deleteEmployer.addEventListener("click", deleteEmployFunc);
row.appendChild(deleteEmployer);

document.querySelector("#Employer").appendChild(row);

This is the function deleteEmployFunc:

function deleteEmployFunc() {
    var id = this.id;

    console.log(id);

    fetch("restservices/employer/" + id, { method: 'DELETE' })
        .then(function (response) {
            if (response.ok) {
                window.location.reload();
            } else if (response.status == 404) {
                console.log("Employer not found")
            } else {
                console.log("Can't delete employer")
            }
        });
}

Answer №1

Ensure that you are attaching the event handler to deleteEmployer rather than deleteEmployerButton

Take a look at this simplified example:

var deleteEmployerButton = document.createElement("input");
deleteEmployerButton.setAttribute("type", "submit");
deleteEmployerButton.setAttribute("value", "delete");
deleteEmployerButton.setAttribute("id", "randomID");

deleteEmployerButton.addEventListener("click", deleteEmployFunc);

document.querySelector("#Employer").appendChild(deleteEmployerButton);



//This is the function for deleting employer

function deleteEmployFunc() {

  var id = this.id;

  console.log(id);

  fetch("restservices/employer/" + id, {method: 'DELETE'} )
      .then(function (response) {
        if (response.ok) {
          window.location.reload();   
        } else if (response.status == 404) {
           console.log("Employer not found")
        } else {
          console.log("Can't delete employer") 
        }            
      });
}
<div id="Employer"></div>

Upon clicking the button, you should see the ID randomID displayed.

Answer №2

this does not pertain to the button on your page. To obtain the id, you can assign a property to your deleteEmployFunc function that references the button and can be accessed within the function itself.

var employer = { employer_id: 1234 };
var deleteEmployer= document.createElement("td");

var deleteEmployerButton= document.createElement("input");

function deleteEmployFunc() {
console.log(deleteEmployFunc.deleteButton.id);
}

deleteEmployerButton.setAttribute("type", "submit");
deleteEmployerButton.setAttribute("value", "delete");               
deleteEmployerButton.setAttribute("id", employer.employer_id);

deleteEmployFunc.deleteButton = deleteEmployer.appendChild(deleteEmployerButton);

deleteEmployer.addEventListener("click", deleteEmployFunc);

document.querySelector("#Employer").appendChild(deleteEmployer);
<div id="Employer"></div>

Answer №3

It has been mentioned in previous responses that you have added the addEventListener to the wrong object. There are several other issues with the code that need attention.

var employer = {
  employer_id: 111
};

//var deleteEmployer= document.createElement("td"); //table and table row objects have their own DOM functions
var row = document.querySelector('#Employer') //a table
  .insertRow(-1); //adding as last row
var deleteEmployer = row.insertCell(-1); //appending to the end of Cells collection of the row

var deleteEmployerButton = document.createElement("input"); //This is fine
// The type attribute is standard, so no need for setAttribute
//deleteEmployerButton.setAttribute("type", "submit");
deleteEmployerButton.type = 'button'; //using button instead of submit since it's not within a form element

deleteEmployerButton.value = "delete";
//unnecessary as shown below
//deleteEmployerButton.setAttribute("id", employer.employer_id);
deleteEmploy.appendChild(deleteEmployerButton); //All good here

deleteEmployerButton.addEventListener("click", deleteEmployFunc(employer.employer_id)); //take note of the function call
//row.appendChild(deleteEmployer); // this operation has already been performed

//document.querySelector("#Employer").appendChild(row); // using table.insertRow(-1) is preferred

//Below is the deleteEmployFunc definition:

function deleteEmployFunc(id) {
  return function() {

    console.log(id);
    /* commented for test / demo purpose
        fetch("restservices/employer/" + id, {
            method: 'DELETE'
          })
          .then(function(response) {
            if (response.ok) {
              window.location.reload();
            } else if (response.status == 404) {
              console.log("Employer not found")
            } else {
              console.log("Can't delete employer")
            }
          });
          */
  };
}
<table id="Employer"></table>

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

Leveraging Vue Data for Storing CSS Properties

I am currently utilizing the Quasar framework in conjunction with Vue for my application development. Below is a snippet of my code: <q-tooltip content-class="bg-amber text-black shadow-4" :offset="[10, 10]"> Save </q-tooltip> <q-tooltip c ...

Is there a way to initiate a callback function once all the contents of an UpdatePanel have been fully loaded?

Looking for a solution with an ASP.NET UpdatePanel that contains multiple images. I am trying to trigger some javascript code after the UpdatePanel is refreshed, but only after all images have finished loading. I attempted using add_endRequest as a callb ...

Issues with ng-bind-html in AngularJS and JavaScript are preventing it from functioning

I am experimenting with creating a dynamic webpage that can change its contents without being limited to predefined templates (potentially offering infinite template options). Below is the code I am currently testing: <!DOCTYPE html> <html lang= ...

How can I retrieve both the keys and values of $scope in AngularJS?

Here is the code I have written to retrieve all key values using $scope. $scope.Signup={}; $scope.Message=''; $scope.SubmitPhysicianSignup = function() { var url = site_url + 'webservices/physician_signup'; //console.lo ...

Navigate Formik Fields on a Map

Material UI text-fields are being used and validated with Formik. I am looking for a way to map items to avoid repetitive typing, but encountering difficulties in doing so. return ( <div> <Formik initialValues={{ email: '&a ...

The spawn function in the child_process module throws an error with the code -2, specifically the

Hey there, I'm working on creating an npx command that allows me to run child commands within my package.json bin: "bin": { "malzahar": "./src/bin/malzahar.js" }, Below is the code from my malzahar.js: #! /usr/bin/en ...

ReactJS displays a collection of items stored within its state

I encountered an issue while trying to display a list of items in my React app with the following error message: Objects are not valid as a React child (found: [object MessageEvent]). If you meant to render a collection of children, use an array instead. ...

Surfing the web with Internet Explorer means music downloads rather than streaming

My music website functions properly, however I am experiencing issues when accessing it through Internet Explorer. The internet download manager is downloading music from the site without any problems in Chrome and Firefox. Is there a way to prevent or b ...

Capture each touchdown and convert it to currency format

As a novice in the field of JS, I have put in a lot of effort into learning from various sources such as websites, documentation, friends, and other questions on Stack Overflow. However, despite all my efforts, I seem to be stuck at this point. $(docume ...

Clicking to remove added child element

I have written a script that creates an image popup when the site loads. Here is the code: <script type="text/javascript"> function showPopup() { var div = document.createElement('div'); div.className += 'popup'; div.inne ...

Utilize the function of express

The following code is not behaving as expected: var express = require('express'); var app = express(); app.use(function(req, res, next) { console.log('first statement'); next(); }, function (req, res, next) { console.log('se ...

Synced Slideshows

Currently experimenting with the Owl Carousel plugin to create multiple synced carousels using their demo at the link below. However, I'm facing a specific issue when dealing with different numbers of small items in each carousel. I've successfu ...

Using React.js to pass data iterated with map function to a modal

I am trying to display my data in a modal when clicking on buttons. The data is currently shown as follows: 1 John watch 2 Karrie watch 3 Karen watch ... like this It is presented in the form of a table with all the 'watch' items being button ...

The click event listener only seems to fire on the second attempt

This block of code is designed to function as a search algorithm that also provides keyword suggestions. When a user clicks on a keyword, it is supposed to be placed into an input textbox. The possible keywords are "first" and "second". However, there is ...

Can one utilize HTML's .querySelector() method to target elements by xlink attribute within an SVG document?

Here is the scenario: <body> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <a xlink:href="url"></a> </svg> </body> Now, can you utilize the HTML DOM's .querySe ...

Dealing with NULL values in a Postgresql database

In the web-survey I created, users are able to select their answers by using radio buttons. To determine which buttons have been selected, I utilize javascript. I have not pre-set any default states for the buttons, allowing users to potentially leave ques ...

Does SameSite=Lax grant permission for GET requests from third-party sources?

After exploring the MDN documentation on SameSite=Lax, I have come to understand the following: In modern browsers, cookies can be sent along with GET requests initiated by a third-party website or during top-level navigations. This is the default behav ...

Troubleshooting problems with dates in jQuery AJAX

Hey, I recently worked on formatting dates in jQuery Ajax. After fetching a date value from the database, I converted it to the format dd-MM-YYYY. However, there seems to be an issue where I'm receiving the previous month. For example, if the database ...

Unable to remove the "d-none" class using Bootstrap 4

Wondering if it's possible to remove the "d-none" class using JavaScript? This is the code snippet I currently have: <div id="progressBar" class="progress d-none"> <div class="progress-bar" role="progressbar" aria-valuenow="0" aria- ...

Determine the most recent API response and disregard any outdated responses from previous calls

I am currently working on a search page where the user can input text into a search box. With each character they enter, an ajax call is made to update the UI. However, I am facing an issue in determining the response from the last API call. For example, i ...