简体   繁体   中英

jQuery selecting hidden input element in same tr different td

I have a problem selecting a hidden input field in the same tr but a different td. Below my Javascript:

function MarkAsChanged() {
    $(this).addClass('changed');
    var $row = $(this).closest('td').prev('td > input[type="hidden"]');
    $row.addClass('changed');
}
$(':input[type="text"]').blur(MarkAsChanged).change(MarkAsChanged);

As you can see I have tried some selectors (var $row). The "this" in the code refers to the input element "blabla-text" in the following HTML code:

<tr>
<td><input type="hidden" value="1" name="blabla-hidden"></input></td>
<td>foo 1</td>
<td>foo 2</td>
<td></td>
<td><input type="text" value="2" name="blabla-text"></input></td>
</tr>

So if you change a value in the input "blabla-text" I want to have the hidden input field to change class to "changed". I cannot work with names/ids in the selector because the table has multiple rows and I only want to post the changed data to my PHP (so I post only the textfields with class=changed). The Javascript works for the textfield but not for the hidden field.

I really hope I am being clear, if not please tell me how I can elaborate.

Thanks in advance!

Try This:

function MarkAsChanged()
{
   $(this).addClass('changed');
   var $row = $(this).closest('tr').find('input[type="hidden"]');
   $row.addClass('changed');
}
$('input[type="text"]').blur(MarkAsChanged).change(MarkAsChanged);

You have to find closest 'tr' tag and use 'find' to find hidden field.

http://jsfiddle.net/ymm6j4rq/

You can use this code as per your table structure :

    <table>
        <tr>
        <td><input type="hidden" value="1" name="blabla-hidden"></input></td>
        <td>foo 1</td>
        <td>foo 2</td>
        <td></td>
        <td><input type="text" onkeyup="MarkAsChanged(this);" value="2" name="blabla-text"></input></td>
        </tr>
    </table>

    <script>



        function MarkAsChanged(curObj)
        {
           $(curObj).addClass('changed');   //curObj is Your Textbox

           var hiddenFieldObj = $(curObj).parent('td').parent('tr').find('td').eq(0).find('input[type="hidden"]');  //hiddenFieldObj is Your Hidden Field

           $(hiddenFieldObj).addClass('changed');             
        }           

    </script>

Hope it should be useful

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