Terminador
Terminador

Reputation: 1398

How to pass value from <a> to click event via jQuery?

I want to pass value "345" by click on <a>

<a class="delete-button'" href="/Customer/Delete/345">Delete</a> 

to this event.

How I can do it?

$(function () {
  function Delete(event) {
   myConfirm('Do you want to delete this record ?',
     function () {
        alert('You clicked OK'); // It should be 345 here
     },
     function () {
        alert('You clicked Cancel');
     },
     'Confirm Delete');
     return false;
}

 $('a.delete-button').click(Delete);

});

Thank you!

Upvotes: 2

Views: 1314

Answers (4)

eliah
eliah

Reputation: 2277

I would do it by putting the "345" in a data attribute on your link tag:

<a class="delete-button" data-customer-id="345" href="/Customer/Delete/345">Delete</a>

Then your delete function can reference it using the .data() method, like so:

function Delete(event) {
   var self = $(this);
   myConfirm('Do you want to delete this record ?',
     function () {
        alert('You clicked ' + self.data("customer-id")); // It should be 345 here
     },
     function () {
        alert('You clicked Cancel');
     },
     'Confirm Delete');
     return false;
}

Upvotes: 3

mVChr
mVChr

Reputation: 50185

Inside your Delete function:

var recordId = this.href.match(/\d+$/)[0];

Upvotes: 1

ahmet2106
ahmet2106

Reputation: 5007

use $.attr(); to get Attributes of any element and use javascript replace() for replacing Strings..

$(function () {
  function Delete(id) {
   myConfirm('Do you want to delete this record ?',
     function () {
        // now you can use the variable "id" for 345...
        alert('You clicked OK'); // It should be 345 here
     },
     function () {
        alert('You clicked Cancel');
     },
     'Confirm Delete');
     return false;
  }

  $('a.delete-button').click(function(){
     var href = $(this).attr('href');
     var id = href.replace('/Customer/Delete/', '');
     Delete(id);
  });
});

Another possibility would be data attributes:

<a class="delete-button'" href="/Customer/Delete/345" data-id="345">Delete</a>

the code above would be:

$(function () {
  function Delete(id) {
   myConfirm('Do you want to delete this record ?',
     function () {
        // now you can use the variable "id" for 345...
        alert('You clicked OK'); // It should be 345 here
     },
     function () {
        alert('You clicked Cancel');
     },
     'Confirm Delete');
     return false;
  }

  $('a.delete-button').click(function(){
     Delete($(this).data('id'));
  });
});

Upvotes: 1

Tango Bravo
Tango Bravo

Reputation: 3309

Try using the jQuery data() function. That way you can bind the data to the element, and access from there, instead of pulling it from the URL.

Upvotes: 0

Related Questions