Finding the input element of next TD

JS1986 picture JS1986 · Oct 24, 2012 · Viewed 11.6k times · Source

having trouble finding the input element in the next td. I need to get place a value into the td class of tblCashSum's textbox.

However, if I do the following:

alert(formElement.nextAll('td.tblCashSum').find('input.cashSum').val());

It reads undefined.

HTML:

<tr>
    <td class='tblCashType'>100</td>
    <td class='tblCashAmount'><asp:TextBox class="inputBox" ID="noteAmount100" runat="server"></asp:TextBox></td>
    <td class='tblCashSum'><asp:TextBox class="inputBoxDisabled cashSum" ReadOnly="true" runat="server" ID="cashSum100"></asp:TextBox></td>
</tr>

Jquery:

$("noteAmount").blur(function(){
 calc($(this));
});

function calc(formElement)
{
    a = formElement.val();
    b = formElement.closest('td').siblings('td.tblCashType').text();
    x = a * b;
    formElement.nextAll('td.tblCashSum').find('input.cashSum').val(x);
}

Answer

undefined picture undefined · Oct 24, 2012

You are passing a string which is the value of the input element, you should first pass the object instead, note that you have missed the # for the ID selector.

$("#noteAmount").blur(function(){
     calc($(this));
});

Then you can use parent and next methods:

function calc($formElement) {
    a = parseInt($formElement.val(), 10);
    b = parseInt($formElement.closest('td').siblings('td.tblCashType').text(), 10);
    x = a * b;
    $formElement.parent().next().find('input.cashSum').val(x);
}

Please note that if your elements have ID attributes you can select them directly which is faster than traversing the DOM.


I can't find an element with ID of noteAmount in your markup, if you have multiple elements with the same IDs your markup becomes invalid and you will get unexpected results , you can also try the following:

$('.inputBox').blur(function(){
    a = this.value
    $this = $(this);
    b = $this.parent().prev().text();
    x = parseInt(a, 10) * parseInt(b, 10);
    $this.parent().next().find('input.cashSum').val(x);
});