How to pass click function data one function to another function in jQuery?

Please see the code to understand my problem.

When I click here.

<a href="#" id="btn-confirm" class="delete" data-id=<%= item._id %>>DELETE</a>

It passes data here

if (window.location.pathname == '/') {
	var modalConfirm = function (callback) {
		$('#btn-confirm').on('click', function (e) {
			e.preventDefault();
			var id = $(this).attr('data-id');
			console.log(id); // Here data is displaying
			$('#mi-modal').modal('show');
		});
	};

	modalConfirm(function (confirm) {
		if (confirm) {
			var id = $(this).attr('data-id');
			console.log(id); // But here I see undefined. How to push data here from the above function?
			var request = {
				url: `http://localhost:3000/employee/${id}`,
				method: 'DELETE',
			};
			$.ajax(request).done(function (response) {
				alert('Data Deleted Successfully!');
				location.reload();
			});
		}
	});
}

How to I can get the data into the second function?

Hey there,
Here’s what I think.
Please read the comments at the end. Also keep in mind that there might be syntax error. I haven’t run it.

if (window.location.pathname == "/") {
  var modalConfirm = function (callback) {
    $("#btn-confirm").on("click", function (e) {
      e.preventDefault();
      var id = $(this).attr("data-id");
      console.log(id); // Here data is displaying
      $("#mi-modal").modal("show");
      callback(whateverYouWantToGiveToConfirm, id);
    });
  };

  modalConfirm(function (confirm, id) {
    if (confirm) {
      // var id = $(this).attr('data-id');
      console.log(id); // But here I see undefined. How to push data here from the above function?
      var request = {
        url: `http://localhost:3000/employee/${id}`,
        method: "DELETE",
      };
      $.ajax(request).done(function (response) {
        alert("Data Deleted Successfully!");
        location.reload();
      });
    }
  });
}
// What happens is this:
// 1- You call modalConfirm on line 12 and pass to it an anonymous function that takes two arguments
// 2- modalConfirm signs up for the #btn-confirm's click event and passes to it another anonymous function
// 3- When #btn-confirm is clicked the anonymous function is called with the right `this` implicitly passed to it.
// 4- Using the correct this you get the `data-id`.
// 5- Now you invoke your callback function that you passed in as an argument in step one and pass to it the id.

Hope that helps!

@alirezaghey Thanks for your reply. But I can’t understand. I’ve solved it in this way.

Used let instead of var and kept it outside of the function.

let id;
var modalConfirm = function (callback) {
	$('#btn-confirm').on('click', function (e) {
		e.preventDefault();
		id = $(this).attr('data-id');
		console.log(id);
		$('#mi-modal').modal('show');
	});
};

Thanks again.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.