1

In the following code is there any possible way to print the string name inside td

<script>

var name = "Myname"

</script>


<td>i have to print the name inside here</td>
    </tr>
</table>

6 Answers 6

4

Here's a way if you can't change any of the html markup:

<script>
    var name = "Myname"

    $(document).ready(function(){
         // Replace all with `name`
         $('td:contains("i have to print the name inside here")').text(name);

         // Add `name` to end
         $('td:contains("i have to print the name inside here")').append(name);

         // Add `name` to beginning
         $('td:contains("i have to print the name inside here")').prepend(name);

         // etc.
    });

</script>
Sign up to request clarification or add additional context in comments.

Comments

4
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

<script>

$(document).ready(function(){
var name = "Myname"

$("#result").html(name);

})



</script>


<div id="result">i have to print the name inside here</div>

Comments

3

Add a identifier to the target td like a class or an id

<td class="name">i have to print the name inside here</td>

then

jQuery(function(){
    $('td.name').text(name)
})

Note: since it is tagged using jquery, I assume jQuery library is already added

Comments

3

Try this script:

<script>

var name = "Myname"

$("#c0r0").text(name);

</script>

For this generated html page:

<table>
    <tr>
        <td id="c0r0">I have to print the name inside here</td>
        <td id="c0r1">Dummy Text</td>
        <td id="c0r2">Dummy Text</td>
    </tr>
    ..............
</table>

2 Comments

Hi George, welcome to Stack Overflow! Don't you mean $("#c0r0").text( name ); so that it's the contents of the variable inserted into the td, not a hard-coded string? Hope this helps!
Haha, sorry. It's very late and I'm just about to go to bed :) no more answering for the day.
1

Check the Js fiddle

http://jsfiddle.net/5EXtz/

var name = "Myname";
$('#mytable tr:first td')
            .each(
                function()
                {
                    //'this' represens the cell in the first row.
                    var tdtxt=$(this).html();
                    var n = tdtxt.concat(name);
                    alert(n);
                }  
            );

Comments

0

Maybe make your own special tag....

var myDataModel = {
    name: 'Sam Chalupka',
  favoriteFruit: 'Lemon',
  age: '45'
};

$('t').each(function() {
  var key = $(this).attr('data');
  var text = myDataModel[key];
  console.log(this);
  $(this).text(text);
});

In html...

<t data="name"></t>
<t data="favoriteFruit"></t>
<t data="age"></t>

Jsfiddle:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.