简体   繁体   中英

How to select a input field in next TD with Jquery?

I want to select a input field in next TD with Jquery. I can not use ID or class because the table's row can be add or removed.

like ,

 <tr>
<td><input type='text' name='price[]' onkeyup = 'getTest(this)' /> </td>
<td><input type='text' name='qty[]' onkeyup = 'getPrice(this)' value='1' /> </td>
<td><input type='text' name='amount[]' /> </td>
</tr>

function getTest(obj){
//I want to select qty[] and amount[]
}

function getPrice(obj){
//I want to select price[] and amount[]
}

anybody know how to select the input fields, please help~!

Thanks

您的网页预期行为的working demo

Chinmayee's answer is much better than this one, but if you don't want to change any of your HTML mark-up, you can simply drop this into your JavaScript and it will work:

    function getTest(obj) {
        var tr = $(obj).closest('tr');
        var qty = tr.find('input[name="qty[]"]');
        var amount = tr.find('input[name="amount[]"]');

        console.log('qty: ' + qty.val());
        console.log('amount: ' + amount.val());

    }

    function getPrice(obj) {
        var tr = $(obj).closest('tr');
        var price = tr.find('input[name="price[]"]');
        var amount = tr.find('input[name="amount[]"]');

        console.log('price: ' + price.val());
        console.log('amount: ' + amount.val());
    }

But the reason why Chinmayee's answer is better than mine is because it uses unobtrusive JavaScript, and it also uses event delegation, so it will perform better.

Here's a possible solution for your problem (assuming you want amount to be price * qty ):

$(document).ready(function(){
  $('[name="price[]"], [name="qty[]"]').live('keyup', function(){
    var inputs = $(this).closest('tr').find('input');
    $(inputs[2]).val($(inputs[0]).val()*$(inputs[1]).val());
  });
});

Your getTest() and getPrice() methods are no longer required with this solution and you can also drop the onkeyup="..." attributes on the input elements.

See here for a working demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM