Skip to content Skip to sidebar Skip to footer

How To Insert Data To A Closest Td With Jquery?

I am trying to get value of an input textbox and insert the value into a td in the same row. Here is my HTML Code:
&l

Solution 1:

.find() looks for the selector in the descendants of input, not the parents. So you need to use $(this).closest('td').

Then, you can use .siblings() like this:

$(this).closest('td').siblings('td.z').text(val);

or

get the nearest tr, and look for a td with z class:

$(this).closest('tr').find('td.z').text(val);

Solution 2:

you can use siblings() for find class "z"

$('.testinp').keypress(function(e){
    if(e.which == 13){
        var val =  $(this).val();
        $(this).closest('td').siblings('td.z').text(val);
    }
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><tableclass="test"><tr ><tdclass="x"><inputtype="text"class="testinp"></td><tdclass="y">Fish</td><tdclass="z">Chicken</td></tr><tr ><tdclass="x"><inputtype="text"class="testinp"></td><tdclass="y">Cricket</td><tdclass="z">Tenis</td></tr><tr ><tdclass="x"><inputtype="text"class="testinp"></td><tdclass="y">Watch</td><tdclass="z">Hat</td></tr></table>

Solution 3:

Here you go with one more solution

$('.testinp').keypress(function(e){
  if(e.which == 13){
      var val =  $(this).val();
      $(this).closest('tr').find('td.z').text(val);
  }
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><tableclass="test"><tr ><tdclass="x"><inputtype="text"class="testinp"></td><tdclass="y">Fish</td><tdclass="z">Chicken</td></tr><tr ><tdclass="x"><inputtype="text"class="testinp"></td><tdclass="y">Cricket</td><tdclass="z">Tenis</td></tr><tr ><tdclass="x"><inputtype="text"class="testinp"></td><tdclass="y">Watch</td><tdclass="z">Hat</td></tr></table>

Traverse till tr using closest and the find td with class z

Hope this will help you.

Solution 4:

Try the following:

$(this).closest('td').next('td').html(val);

.find doesn't go up in the DOM, it goes down. So you won't find any td that are under your input field.

Edit: Sorry, forgot to remove the . point. I copied and edited your approach, it should say .next("td") of course.

Solution 5:

Try this

$('.testinp').keypress(function(e){
    if(e.which == 13){
        var val =  $(this).val();
        $(this).parent().parent().find('td').closest('.z').html(val);

    }
});

Post a Comment for "How To Insert Data To A Closest Td With Jquery?"