简体   繁体   中英

How do I get the value of td and pass it on input in each td element?

I'm still a newbie in jQuery world :) I am making something that looks like this and my problem is getting the text in each <td> and passing it to the input.

I have this code:

<div class="grid-l1">
  <table>
    <tr>
      <td>
        Testing
        <input type="text">
      </td>
    </tr>
    <tr>
      <td>
        Testing 2
        <input type="text">
      </td>
    </tr>
  </table>
    <span class="edit">Edit</span>
    <span class="update">Update</span>
</div>

Here's my jQuery code:

<script>
    $(document).ready(function(){
        $('body').on('click', '.edit', function() {
            $(this).hide();
            $('table tr td input').show();
            $('.update').show();
        });

        $('.update').click(function(){
            $(this).hide();
            $('table tr td input').hide();
            $('.edit').show();
        });
    });
</script>

How do I get the td text and pass it into each input on td element when I click edit ?

I will appreciate every response you guys will be doing. Thanks in advance.

What you need is to get the text of td with text() , then add it to input val .

Here the code:

$(document).ready(function(){
    $("input").hide();
        $('body').on('click', '.edit', function() {
            $(this).hide();
            $("table td").each(function() {
                $(this).find("input").val($.trim($(this).text()))
            });
            $('table tr td input,.update').show();
        });

        $('.update').click(function(){
            $(this).hide();
            $('table tr td input').hide();
            $('.edit').show();
            $("table input").each(function() {
                $(this).parent().text($(this).val())
            });
        });
    });

Demo : http://jsfiddle.net/1yz8dc3t/

You would need to get the text() of the td that contains the input and set it's value. Try this:

$('body').on('click', '.edit', function() {
    $(this).hide().closest('div').find('table input').val(function() {
        return $.trim($(this).closest('td').text());
    });
    $('table tr td input, .update').show();
});

Example fiddle

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