Reputation: 425
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.
Upvotes: 1
Views: 1362
Reputation: 7004
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/
Upvotes: 0
Reputation: 337570
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();
});
Upvotes: 1