views:

38

answers:

2

I have a view that will create a table while enumerating over each item in my model. to each row I need to add a button. I need would like to have a jquery function tied to each button to show an alert when it is clicked. the text will be different depending on the row item that is clicked, so I must know what row the edit button is in that was clicked. does that make sense? And how would I do this?

so here is what I have

<table>
<% foreach (var item in Model)
       { %>
<tr>
<td><%=Html.encode(item.id) %></td>
<td><%=Html.encode(item.id) %></td>
<td><button id="button<%=item.id%>">select<button>
</tr>
<%}%>
</table>

something like that. How do I try a jquery function to each button. Is this possible? Thank you!

+3  A: 

not tested but should work:

$(function){
    $('[id^=button]').click(function(){
        var itemId = $(this).attr('id').substring(6);
        alert(itemId);
    });

}

basically you add the click event to everything that has an id that starts with button. and you get the item's id but getting the substring from the buttons id attribute.

Patricia
[id^=button] Very good to know. i have a long ways to go to mastering jquery.Worked perfectly. Thank you!
twal
glad it helped!
Patricia
+1  A: 

The following will find all buttons in a table which have an id beginning with 'button'. Based on your example this would find all of your databound buttons and attach an onclick handler which would display an alert displaying the button's unique id.

$('table tr td button[id^=button]').click(
function (e) {
alert($(this).id);
e.preventDefault();
});

You could then amend this to fit your needs.

Brian Scott
Thank you as well. This is very good to know!
twal
@twal: You should pay particular attention to the selector options as they often make things a lot easier when working out how to get certain elements. http://api.jquery.com/category/selectors/[id$=button] -- ends with 'button', [id!=button] -- is not 'button', [id*=button] -- contains 'button',
Brian Scott