0

I'm using JQuery I have a table inside a razor view... I want to get a value(StudentID) according to a click on an img that I have in the same row, I want to get the value and then send it to an Action Method in the Controller class as a parameter. With this sentence I'm just getting an string, for example if a click the img element and in that row the value of StudentID is 129, then the value of id is

"\n 129 \n"

I'm expecting id to have the value 129. This is the sentence, what I need to change? I've tried using innertext() but JQuery doesn't recognize it

var id = $(this).parent().siblings().eq(3).text()

If you want to consult the table this is:

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Age)
        </td>
        <td style="display:none" id="tdStudentID">
            @Html.DisplayFor(modelItem =>item.StudentID)
        </td>
        <td>
            <img src="~/images/deleteIcon.png" width="20" height="20" class="imgJQuery" />
        </td>

    </tr>
}
8
  • 1
    try this selector var id = $(this).closest('tr').find('#tdStudentID').text() Commented Jul 9, 2016 at 4:50
  • try this selector var id = $(this).closest('tr').find('#tdStudentID').text() i would also suggest to use class instead of ID as you loop you will create duplicated ID and ID should always be UNIQUE. so your selector will be var id = $(this).closest('tr').find('.tdStudentID').text() Commented Jul 9, 2016 at 4:56
  • @guradio you're right about use class attribute and not id, but still I'm getting the same result: "\n 129\n " I tried using the selector you gave me but it's getting the same result Commented Jul 9, 2016 at 5:00
  • can you create a demo or snippet so SO people can actually see the problem in action? Commented Jul 9, 2016 at 5:04
  • 2
    Much easier if you just use <img src="..." class="imgJQuery" data-id="@item.StudentID" /> and then $('.imgJQuery').click(function() { var id = $(this).data('id'); ..... }); Commented Jul 9, 2016 at 5:06

1 Answer 1

1

Add student id as data attribute on the image instead of putting it inside a hidden td, like

<td> <img src="~/images/deleteIcon.png" width="20" height="20" class="imgJQuery" data-student-id='@Model.StudentID'/> </td>

Then simply catch it like that

$('img').data('student-id')
Sign up to request clarification or add additional context in comments.

1 Comment

Yes that's the answer as Stephen Muecke said too, very easy doing it using data- attribute inside img tag, thnxs

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.