xSea xSea - 2 months ago 8
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>
@ul.Email
</td>
<td>
@ul.Fullname
</td>
<td>
@ul.Company.Name
</td>
<td class="hidden">
<input type="hidden" name="UserId" id="UserId" value="@ul.Id" />
</td>


Jquery

function textover(id) {
$('#Email').val($(id).find("td").eq(0).text().trim());
$('#Fullname').val($(id).find("td").eq(1).text().trim());
$('#Company').val($(id).find("td").eq(2).text().trim());
$('#IdNo').val($(id).find("td").text(3).trim());

Answer

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();
alert(userId);
$('#IdNo').val(userId);

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" />
        </td>
</tr>

and the script to handle the row click event

$(function(){
  $("tr.selectableRow").click(function(e){    
        var email = $(this).find(".email").val();
        var fullName = $(this).find(".fullName").val();
        // do something with these    
  });    
});