开发者

jquery how to find selector with similar ID in table row

I have a table that per row has some inputs and one edit button. I need to when user click edit button, I can get inputs value in this row and I do another action. I use this code, but not work.

$("#editRowButton").click(function () {
     var currentTablerow = $(this).parent().parent();
     var txtNameValue = $(currentTablerow).find('input[id*="txtName"]').val();
});

My table structure like this

  <table id="Table2">
        <thead>
            <tr>
                <th>
                    Name
                </th>
                <th>
                    Family
                </th>
                <th>
                </th>
            </tr>
        </thead>
        <tbody>
            <tr class="itemRow">
                <td>
                    <asp:TextBox Width="70px" ID="txtName" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:TextBox Width="70px" ID="txtFamily" runat="server"></asp:TextBox>
                </td>
                <td>
                    <img id="editRowButton"  src="../Images/Edit.gif" />
                </td>
            </tr>
                    </tbody>
    </table

> itemRow repeat by asp.net li开发者_如何转开发stview control Problem occurs in below code

 var currentTablerow = $(this).parent().parent();
    var txtNameValue = $(currentTablerow).find('input[id*="txtName"]').val();

How i replace find by another solution


Firstly, you cannot have multiple elements with the same ID. Secondly, it would be much easier to write the following code like so

$(".editRowButton").live('click', function () {
    // To get the closest parent element that is a table row
    var currentTablerow = $(this).closest('tr');
    // To get all of the inputs
    var inputs = currentTablerow.find('input');

    // use the values
    alert(inputs.filter('.name').val());
});

This also means that your html should resemble something like

<tr>
    <td><input type="text" class="name" /></td>
    <td><input type="text" class="email" /></td>
    <td><button class="editRowButton">Edit</button></td>
</tr>


In this code, what happens if that find call returns more than 1 input field? You can't get the value from an array like that, you would need to loop over it and do something with each value.

Further, what doesn't work? Maybe you can put a concise example on http://jsfiddle.net/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜