开发者

jquery closest tr and finding an element

I have the following code

<form name="frm1">
<table id="mytable" border="1" cellspacing="2" cellpadding="2">
    <tr>
        <td>
            column1
        </td>
        <td>
            column2
        </td>
        <td>
            column3
        </td>
    </tr>
    <tr>
        <td>
            ABC
        </td>
        <td>
            <select name="mydd" class="mydd">
  开发者_如何学C              <option value="ABC">ABC</option>
                <option value="DECF">DECF</option>
                <option value="GHHHH">GHHHH</option>
            </select>
        </td>
        <td>
            <input type="text" name="textvalue" id="textvalue" value="kljaslkjd">
        </td>
    </tr>
    <tr>
        <td>
            ABC
        </td>
        <td>
            <select name="mydd" class="mydd">
                <option value="222">222</option>
                <option value="333">333</option>
                <option value="444">444</option>
            </select>
        </td>
        <td>
            <input type="text" class="textvalue" name="textvalue" id="textvalue" value="kljaslkjd">
        </td>
    </tr>
</table>
</form>

jquery code as below:

$(document).ready(function(){
    $(".mydd").change(function(){
      var value= $(this).closest("tr").find(".textvalue").attr("name");
       alert('value:' + value);
    });
});

What I am trying to do is, when I change the drop down option, I am getting the closest tr, and then finding for an input element. The first element is always returning undefined. But the second element works fine. What could be the reason?


The first <input> is missing the textvalue class. Change

<input type="text" name="textvalue" id="textvalue" value="kljaslkjd">

to

<input type="text" class="textvalue" name="textvalue" id="textvalue" value="kljaslkjd">

The markup also contains multiple elements with duplicate IDs, which is invalid HTML. So also change the first id="textvalue" to id="textvalue1" and the second to id="textvalue2".


Duplicated IDs - they'll get you every time. That could be the issue here. Secondly, the first one doesn't have the right class - or a class, for that matter.


I suggest you that you always always use both options for your html tags (name, id) because you can have two elements with the same name and there's no problem at all, but the id it has to be unique and the id is what it's important for javascript, and the name is important for the server language like PHP.

And the input tags from where you are triggering this, have no class textvalue, so maybe that's the problem.


The <input> in the first row has no class="...".
Therefore, .textvalue doesn't find it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜