0

I create a grid in C# MVC 3. and place a delete button in every rows in the grid.

Please see my image below.

enter image description here

Delete button code.

<td>
 <button id="removefromcart" type="button" name="removefromcart" 
          class="remove-cartitem" value="@(item.Id)"> </button></td>

Script :

<script type="text/javascript">
$(document).ready(function () {

    $('[name="removefromcart"]').click(function () {
        alert('clicked');
    });

})

I try to alert the value of the clicked button.

Please help

2
  • 1
    are you getting alert ? Commented Apr 19, 2013 at 7:27
  • Yes. with " clicked "... But how to get the value of clicked button ? Commented Apr 19, 2013 at 7:28

5 Answers 5

2

use class attribute of dom element

<script type="text/javascript">
$(document).ready(function () {

$('.remove-cartitem').click(function () {
    alert($(this).val());
});

});
</script>
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

$('.remove-cartitem').click(function () {
    alert($(this).attr('value'));
});

Comments

1
 $('[name="removefromcart"]').click(function () {
        alert($(this).val());
 });

Comments

1

Your button has an id, i guess it would be better to use this ID to get the element in jquery.

Moreover, the click() function is deprecated, you should use on('click') which allows you to unbind the event with off('click').

$('#removefromcart').on('click', function() {
    alert( $(this).val() );
});

The best way would be not to use jQuery

document.getElementById('removefromcart').addEventListener('click', function() {
    alert( this.attributes.value.nodeValue );
});

Hope this helps :)

Comments

1

Simply get the value of the DOM element :

$('[name="removefromcart"]').click(function () {
    alert(this.value);
});

EDIT :

this.value is equivalent to $(this).val() or $(this).attr('value') but fastest since we only manipulate DOM attribute (and not a jQuery object)...

See for example : jsPerf

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.