Johan Björklund
Johan Björklund

Reputation: 774

Putting a TD value as its text

Is it possible to take the value of a TD, and placing it as its text?

<td class="itemtd" value="58057" bgcolor="red"></td>

I can't seem to read the value, or even check if it exists, this is what I've tried so far, but it does not work

<script>
$(function(){
    $('.itemtd').each(function(){
        if ($(this).val() != '') {
        $(this).append($(this).val());
        }
    });
});
</script>

Upvotes: 0

Views: 922

Answers (4)

Aneudy Guzman
Aneudy Guzman

Reputation: 19

If you want to get the value attribue of the TD, then call the data method of the element, so change if ($(this).val() != '') to if ($(this).data('value'))

and then to add the value to the TD element, change:

$(this).append($(this).val()); to $(this).html($(this).data('value'));

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly td elements cannot have a value attribute. Adding one can will make your code invalid which can lead to rendering errors. To fix this, use data-* attributes to store custom data in your HTML:

<td class="itemtd" data-value="58057" bgcolor="red"></td>

Then in your JS you don't need to use each() as you can provide a function to text() which acts on each matched td individually. Try this:

$('.itemtd').text(function(i, text) {
    return text == '' ? '' : text + $(this).data('value');
});

Working example

Upvotes: 0

toomanyredirects
toomanyredirects

Reputation: 2002

TD's do not have a value property. If you want to set one, use a data attribute instead:

<td class="itemtd" data-value="58057" bgcolor="red"></td>

Then use jQuery.data() to access the property:

<script>
$(function(){
  $('.itemtd').each(function(){
    $(this).html($(this).data('value'));
  });
});
</script>

You don't need to append if it's the only thing you're putting in the td, jQuery.html() will suffice. You also don't need to check the contents isn't empty because if it is then it'll just put an empty string in between.

Upvotes: 4

IrkenInvader
IrkenInvader

Reputation: 4050

You should be able to use jquery attr and html to grab the value and place it inside the tag:

<script>

    $(function(){
        $('.itemtd').each(function(){
            if ($(this).attr('value') != '') {
              $(this).html($(this).attr('value'));
            }
        });
    });

</script>

Upvotes: 4

Related Questions