Reputation: 4761
Is the following possible to accomplish?
Given a string of table cells:
var str = "<td></td><td></td><td></td>";
Is that possible to convert this string into a jQuery object like this and add text to any table cell by the index:
var index = 1;
$(str).eq(index).text("Some text");
And after that convert the object back into a string to concatenate with the rest of the table cells in an existing table.
The code above does not seem to work. Is there any way to do this?
Thanks.
Upvotes: 2
Views: 1325
Reputation: 21482
To convert back to a string, you could try:
var str = "<td></td><td></td><td></td>";
var $celts = $(str);
$cells.eq(1).text("Some text");
str = $('<div></div>').append($cells).html();
But you should be able to accomplish what you want without converting this back into a string.
Upvotes: 0
Reputation: 19005
Manipulating with just a string:
var str = "<td></td><td></td><td></td>";
var desiredIndex=1;
var desiredText="Some Text";
var output="";
var tmp=str.split("</td>").slice(0, -1);
for(var i=0;i<tmp.length;i++){
output+=tmp[i];
if(i==desiredIndex){output+=desiredText;}
output+="</td>";
}
alert(output);
Upvotes: 1
Reputation: 5187
Here is a possible solution:
First, your string should be added to a table. Then, you can insert text in the cell you want to. Here is an example code:
$('#insert1').on('click', function(){
var thirdCell = $('#datatable >tbody').find('tr:first > td')[2];
$(thirdCell).text('100');
});
$('#insert2').on('click', function(){
var secondRow = $('#datatable >tbody').find('tr')[1];
var secondCell = $(secondRow).find('td')[1];
$(secondCell).text('200');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="datatable">
<thead><tr><td>Column A</td><td>Column B</td><td>Column C</td></tr></thead>
<tbody>
<tr><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td></tr>
</tbody>
</table>
<br/>
<button id="insert1">Insert value in 3rd cell in 1st row</button>
<br/>
<br/>
<button id="insert2">Insert value in 2nd cell in 2nd row</button>
Upvotes: 0
Reputation: 21
use jquery each() function to solve this. like following....
$('td').each(function(k,v){
if(k==1){
$(this).html("my text");
}
});
Upvotes: 0