user745110
user745110

Reputation: 119

apply values of inputs to all its td innerhtml

is it possible to change the innerhtml of all the td when it has the input inside, i mean to take the input's value and apply it to it's td innerhtml, for example, here's the table and its input inside:

<table>
 <tr>
  <td><input value="test" /></td>
  <td>123</td>
 </tr>
</table>

to change it smth into this:

<table>
 <tr>
  <td>test</td>
  <td>123</td>
 </tr>
</table>

for all of the td and input values without applying id's and classes?! please pay attention that td innerhtml didnt change :) thank you all for the help! ;)

Upvotes: 3

Views: 1790

Answers (3)

Lasse Espeholt
Lasse Espeholt

Reputation: 17782

Yes, you can do it like this:

$('table td:has(:input:only-child)').each(function () {
    $(this).html($(':input', this).val());
});

It assumes there only is an input in the td. If that is not the case, then remove :only-child.

Explanation of table td:has(:input:only-child)

It says, take any td within a table, which has an input as the only child.

You can test it here: http://jsfiddle.net/eydtw/

Update: take the input which is not hidden.

$('table td:has(input[type!="hidden"])').each(function () {
    $(this).html($('input[type!="hidden"]', this).val());
});

http://jsfiddle.net/eydtw/1/

or: take the input which is text.

$('table td:has(input:text)').each(function () {
    $(this).html($('input:text', this).val());
});

http://jsfiddle.net/eydtw/3/

Upvotes: 4

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

That's pretty easy.

Name your table first (to find it easily).

<table id="the_table">
 <tr>
  <td><input value="test" /></td>
 </tr>
</table>

Then you can do this:

$('#the_table td input[type="text"]').each(function() {
  var val = $(this).val();
  $(this).parent('td').html(val);
});

Live demo.

Explanation:

  1. find all inputs that are within <td> that are in this certain table.

  2. for each input:

    2.1 retrieve value from the input

    2.2 find first parent of the input that is a <td> tag and set its innerHTML to that value

Upvotes: 5

Ali Foroughi
Ali Foroughi

Reputation: 4609

$.each($('table td'),function(){

    if($(this).children().length !=0)
    {

        var temp = $($(this).children()[0]).val();
        $(this).html(temp);

    }

})

Upvotes: 1

Related Questions