jQuery is failing to properly render dynamic content data identifiers

Need help with a dynamic HTML div

<a data-id="17" onclick="getcustomer();">
    <div class="note note-success">
        <h4 class="block">A</h4>
        <p>Email : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f998b99e94989095d79a9694">[email protected]</a></p>
        <p>Mobile : 8</p>
        <p>DOB : 0000-00-00</p>
    </div>
</a>

When the above anchor is clicked, it triggers this function

function getcustomer(){
    var id = $(this).data('id');
    alert (id);      
    $.post(base_url+'who/customer', {
        customer_id: id
    }, function(data, status){
        console.log(data);
    });
}

However, the alert shows undefined.

How can I retrieve the value of data-id?

This field is dynamic and the 'a' elements are added after the DOM is loaded.

Answer №1

this is not referencing the element, but instead it refers to window

Pass this as an argument for the getcustomer function

function getcustomer(elem) {
  var id = $(elem).data('id');
  alert(id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a data-id="17" onclick="getcustomer(this);">
  <div class="note note-success">
    <h4 class="block">A</h4>
    <p>Email : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="325372555f535b5e1c515d5f">[email protected]</a></p>
    <p>Mobile : 8</p>
    <p>DOB : 0000-00-00</p>
  </div>
</a>

Alternatively, utilize jQuery event binding using .on method

$('.eventBinding').on('click', function() {
  var id = $(this).data('id');
  alert(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a data-id="17" class='eventBinding'>
  <div class="note note-success">
    <h4 class="block">A</h4>
    <p>Email : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5534153238343c397b363a38">[email protected]</a></p>
    <p>Mobile : 8</p>
    <p>DOB : 0000-00-00</p>
  </div>
</a>

Answer №2

Hand over the object to the method,

<a data-id="17" onclick="getcustomer(this);">

After that, the code will look like this:

function getcustomer(obj) {
  var id = $(obj).data('id');
  alert(id);
  $.post(base_url + 'who/customer', {
      customer_id: id
    },
    function(data, status) {
      console.log(data);
    });
}

Answer №3

Give this a shot:

<div data-id="17" onclick="fetchCustomer(this);">

function fetchCustomer(current_element){
    var id = $(current_element).data('id');
    alert(id);

   $.post(base_url+'who/customer',
   {
       customer_id: id
   },
   function(response, state){
       console.log(response);
   });
}

Answer №4

Have you considered utilizing $(this).attr('data-id');

Answer №5

Give this a shot too, see if it does the trick. It's a simple one-liner.

$('a').on('click', function(){
    var id = $(this).attr("data-id");

    alert(id);
});

Alternatively, you could experiment with this based on your existing code:

function retrieveCustomer(){

var id = $(this).attr('data-id');
alert (id);

$.post(base_url+'who/customer',
{
    customer_id: id
},
  function(data, status){
      console.log(data);
  });
}

Answer №6

Here is an example script to retrieve customer information:

function findCustomer(){

    var customerId = $(this).attr('data-customerid');
    alert (customerId);

    $.post(base_url+'find/customer',
    {
        id: customerId
    },
    function(response, result){
        console.log(response);
    });
}

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

Could there be a more efficient method to enable support for all video formats?

I have a case statement in my video validation function that checks for specific file extensions of video formats. However, I am wondering if there is a shorter way to write the code in order to allow all video formats instead of creating a long list of al ...

The accumulation of input using setInterval is not effective

I need some help with my code. Please take a look at this link here. I want the input to count up from zero and hide when I click the "change" button. But when I show the input again, I want its value to reset back to zero. Can anyone guide me on how to ...

create a division in the organization of the identification numbers

Is there a way to always change pages when the id changes in a foreach loop to separate the printed pages? Take a look at this code snippet: var data = [ {Id: "552", valor: "50.00", Descricao: "Fraldas", }, {Id: "552", valor: "35.00", Descrica ...

Obtaining a date and time in PHP from a JavaScript array

I am currently working on implementing a JQuery datetime picker and my goal is to save the selected date and time into a PHP variable for storage in a MySQL database. Despite browsing through various examples, none of them seem to be effective in achieving ...

Integrating Python Script with User Input and Output within a JavaScript Web Application

I have an existing JS website that requires additional functionality, and after some research I believe Python is the best tool to handle the necessary calculations. My goal is for users to input information that will then be used as input for my Python ...

Is it possible to execute in a specific context using npm?

I am seeking to execute npm scripts that are executable by VuePress. For instance, I have VuePress installed and would like to run the command vuepress eject. Although I can access vuepress in my scripts, there is no specific script for eject: "scr ...

The WebRTC video feature is functioning on the local network but is encountering difficulties

Trying to grasp WebRTC has been quite the journey for me. In an attempt to troubleshoot my failed video transfer between computers, I uploaded what I have so far onto a temporary github repository: https://github.com/stevendesu/webrtc-failure My goal is ...

The specified type does not meet the constraint as it lacks the required index signature

I'm currently working on refactoring a TypeScript project that utilizes React Hooks. While I have some knowledge of TypeScript, I am still more of a beginner than an expert. My main goal is to create reusable code for this project through the use of ...

Utilize jQuery setInterval to dynamically add and remove classes on elements

My goal is to display my image in a way that resembles waving flames. I decided to achieve this effect by using two layers (flame tongues) stacked on top of each other in the same position. My initial approach was to hide one flame tongue while showing the ...

Verify if the item already exists in the Vue.js array

Here is the data I have: data: function() { return { conversations: [ ] } } I am retrieving my data from the response object using response.data.conversation Is there a method to verify if this.conve ...

Having difficulty retrieving an item from a knockout observable array

When fetching data from a web API and pushing it into an observable array, I wanted to make the items in the array observable as well. Unfortunately, I found that I couldn't access the object if I made it observable. function UpdateViewModel() { ...

What is the correct way to upload an image using the Express static middleware?

Just diving into express, I have this setup in my server: app.use(express.static(path.join(__dirname, 'includes'))); When it comes to my client-side JavaScript, I'm simply using the URL like so: var img = $("<img />").attr('s ...

Any tips for filtering an array within an array of objects using the filter method?

I have an array of products and models that I am currently filtering based on 'id' and 'category'. var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.products = [{ 'id': 1, ...

What steps can be taken to safeguard data while navigating within the Angular framework?

I am facing an issue with storing an array of items in a service (referred to as cart service) and displaying it in the component (cart.component.ts). The components bgview.component.ts and single.component.ts are involved in selecting individual items, wi ...

Tips for controlling the size of a canvas element: setting minimum and maximum width and height properties

function convertImageResolution(img) { var canvas = document.createElement("canvas"); if (img.width * img.height < 921600) { // Less than 480p canvas.width = 1920; canvas.height = 1080; } else if (img.width * img.he ...

The Bootstrap dropdown functionality is not working properly and fails to open when clicked

Can anyone help with this Navber code issue? <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #FDFEFF;"> <div class="collapse navbar-collapse justify-content-center" id="navbarNav"> <a class="navbar-brand" ...

easy method for creating a hyperlink that triggers a "download" pop-up box

Is there a simple and efficient way to have some of my links trigger the 'save file as' prompt (similar to right-clicking) immediately after they are clicked for the first time? ...

When attempting to trigger a function by clicking a button in Angular 8 using HTTP POST, nothing is happening as

I've been struggling to send a POST request to the server with form data using Observables, promises, and xmlhttprequest in the latest Angular with Ionic. It's driving me crazy because either I call the function right at the start and the POST wo ...

Manually assigning a value to a model in Angular for data-binding

Currently utilizing angular.js 1.4 and I have a data-binding input setup as follows: <input ng-model="name"> Is there a way to manually change the value without physically entering text into the input field? Perhaps by accessing the angular object, ...

A guide to organizing elements in Javascript to calculate the Cartesian product in Javascript

I encountered a situation where I have an object structured like this: [ {attributeGroupId:2, attributeId: 11, name: 'Diamond'}, {attributeGroupId:1, attributeId: 9, name: '916'}, {attributeGroupId:1, attributeId: 1, name ...