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

Is it advisable to perform unit testing on my JavaScript code?

I'm interested in exploring the potential value of using QUnit. However, I am completely new to testing, especially with JS, and don't know where to begin. I would appreciate any guidance on starting unit testing for an application that already ...

The back-end code on the server is unable to identify the variable in my req.body, as it is being flagged

At the moment, I am in the process of developing a web application that needs to transmit data from the client side to the server side whenever a specific button is clicked. However, when I click the button, the terminal consistently informs me that the va ...

Error Message: A key is being provided to the classes property that is not implemented in the current context

Trying to customize Material-UI styles with makeStyles() as outlined in the documentation but encountering a warning when passing a classname in the parent component that is not specified in useStyles. The warning message reads: Warning: Material-UI: th ...

Is there a way to halt the compiler until an Ajax request is fully processed?

Within my form, there is a field labeled parent keywords as a secret key. The validation of this form using JavaScript functions smoothly. It is designed to check if the secret key is associated with any parent or not. If not, the value is set to 0 by defa ...

Dynamically loading an iFrame source and automatically populating input forms using Javascript explained

My current challenge involves retrieving URL parameters successfully and using them to decide which iframe src to populate. Additionally, I need to autofill the form created via the form src with other parameters. However, I am faced with two main issues. ...

The issue arises when the export function is triggered within the getStaticPaths() method, preventing the top-level

For my Next.js SSG (static site generation) app, I decided to optimize the database connection process by exporting a global promise from one file and then utilizing it in another file called controllers.js. This file houses multiple functions that directl ...

What is the best way to dynamically duplicate the Bootstrap multi-select feature?

$(function() { $('#days').multiselect({ includeSelectAllOption: true }); $('#btnSelected').click(function() { var selected = $("#days option:selected"); var message = ""; selected.each(function() { message ...

Guide on parsing the obj variable into a webix .show() modal?

I have a piece of code that looks like this: $$('TLVab').attachEvent("onAfterEditStop", function(state, editor, ignoreUpdate) { $$('deleteLTMPopup').show();//TODO parse state into the pop up }); UI.deleteLTMPopup= {id:& ...

How can I ensure that all row checkboxes are automatically marked as checked upon loading the Material Table in ReactJS?

I'm currently working on a project using React Material Table and I need to have the selection option pre-checked by default. Is there a way to accomplish this? function BasicSelection() { return ( <MaterialTable title="Basic Selec ...

Unable to dynamically display an HTML5 video using JavaScript

I'm facing an issue with displaying videos in a modal dynamically. Here's the scenario: +------------+---------+ | Name | View | +------------+---------+ | 1.mp4 | X | | 2.mp4 | X | +------------+---------+ The X ...

Are you curious about the array of elements in React's carousel?

I'm currently in the process of constructing a website using React, and I have a specific challenge related to the "news" section. Within this section, I have a list of three components that represent different news items. These components are housed ...

Adding tween.js seems to have caused the button click event to stop triggering

After adding the code line to tween my display box, the click event is no longer triggered. There are no errors in the console. How can I resolve this issue and what might have caused it? createjs.Tween.get(directionsbox, { loop: false }).to({ x:800, y: ...

Emphasizing the date variable within a spreadsheet

Hey there! I'm struggling with the code below: <html> <head> <title>highlight date</title> <style> .row { background-color: Yellow; color:blue; } </style> <script type="text/javascript"> </script> &l ...

Using jQuery to retrieve values from clicked buttons

I'm trying to retrieve the values of a jQuery button upon form submission, but my current setup is not working. Specifically, I need to extract the value of data-url. Below is the code snippet I am using: $("#addAgency").submit(function(event) { ...

Why does my WCF REST web service escape the JSON string response for weakly-typed JSON?

I am currently working with a contract that looks like this: [ServiceContract] public interface IServiceJsonContract { [WebInvoke(UriTemplate = "/MyMethod", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST" ...

Having difficulty creating a shadow beneath a canvas displaying Vega charts

I'm looking to create a floating effect for my chart by adding shadows to the canvas element that holds it. Despite trying various methods, I can't seem to get the shadow effect to work. Here is the code snippet I have for adding shadows: <sc ...

Troubleshooting ASP.NET MVC3: The mystery behind why my custom validation attributes always seem to fail

After completing several tutorials, I have successfully implemented my models from a library file (dll). Everything seems to be functioning correctly except for one issue. Here is my model: public class RoomBookingInsert { public Int32 CostCentreNo ...

Looking for assistance with arranging and managing several containers, buttons, and modals?

My goal is to create a grid of photos that, when hovered over, display a button that can be clicked to open a modal. I initially got one photo to work with this functionality, but as I added more photos and buttons, I encountered an issue where the first b ...

Deactivating Node.js files in vsCode for client-side JavaScript files

I'm facing a major challenge when it comes to coding with JavaScript. I have a JavaScript file that is using Node.js, which means I am unable to manipulate the DOM elements. Take this code snippet for example: var form = document.getElementsByClassNa ...

jQuery-chosen - Transfer custom attribute from chosen option to list when selected

I have a selection list as shown below: <select data-placeholder="Choose users" style="width:350px;" multiple class="chosen-select" tabindex="8"> <option data-user-id="1">User1</option> <option data-user-id="3">User2</op ...