繁体   English   中英

使用jQuery更改列文本框值时如何获取表行索引

[英]How to get table row index when the column textbox value change using jQuery

价格表文本框值更改时,我想获取行索引和文本框值。 目前,我正在获得一些未定义的值。

的HTML

<table class="table table-striped">
    <thead>
        <tr>                   
            <th>Product</th>                              
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <input type="text" class="form-control product">
            </td> 
            <td>
                <input type="text" oninput="javascript:GetValue(this);" class="form-control price">
            </td>
        </tr>
    </tbody> 
</table>

的JavaScript

function GetValue(oTextBox) {
    var price = oTextBox.value;
    var product = oTextBox.parent().prev().innerHTML.value;
    var rowindex = oTextBox.closest('tr').index();
}

我收到此错误:

TypeError:oTextBox.parent不是函数var product = oTextBox.parent()。prev()。innerHTML.value;

用$(oTextBox)替换函数中的oTextBox,然后可以使用html()代替innerHTML,如下所示

$(oTextBox).parent().prev().html()

您需要在$中包装oTextBox才能使用jQuery方法。 这是因为oTextBox ...或... this是一个DOM元素,而不是jQuery对象。 从而:

var product = oTextBox.parent().prev().innerHTML.value;

应该:

var product = $(oTextBox).parent().prev().find('input').val();

和:

var rowindex = oTextBox.closest('tr').index();

应该:

var rowindex = $(oTextBox).closest('tr').index();

建议

我鼓励您不要使用内联JS:

<input type="text" class="form-control price">

然后您的jQuery将是:

$(function() {
    $('input.price').on('input', function() {
        var price = this.value;
        var product = $(this).parent().prev().find('input').val();
        var rowindex = $(this).closest('tr').index();
        //....
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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