xSea xSea - 1 year ago 74
Javascript Question

Jquery get and set Value

I have this code that can get value from the td and pass it to other mvc view. but somehow i cant get the value of Hidden class properties?

<tr onclick="textover(this)">
<td class="hidden">
<input type="hidden" name="UserId" id="UserId" value="@ul.Id" />


function textover(id) {

Answer Source

This piece of code .text(3), is the bad guy!

text method does not have an overload which takes the array index!. So that line of code should crash!

It is not very safe to use the eq method with index to get an item. What if tomorrow you add one more new td in the middle and now you have to fix a bunch of index values with eq method calls!

Why not use the selector which specify the name attribute value ? Also for the input field, you need to get the value using the val() method.

var userId = $(id).find("input[name='UserId']").val();

IMHO, yo may give a css class to the td's and use that for your jQuery selection instead of relying on the indexes. Also you may consider doing your javascript in an unobtrusive way.

<tr class="selectableRow">
        <td class="email"> @ul.Email</td>
        <td class="fullName"> @ul.Fullname </td>
        <td class="companyName"> @ul.Company.Name 
            <input type="hidden" name="UserId" id="UserId" value="@ul.Id" />

and the script to handle the row click event

        var email = $(this).find(".email").val();
        var fullName = $(this).find(".fullName").val();
        // do something with these    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download