0

Can jQuery be used in order to tranform this code:

<table>
    <tr>
        <td><input type="text" name="a1" value="Input value 1" /></td>
        <td><input type="text" name="a2" value="Input value 2" /></td>
        ...
        <td><input type="text" name="a10" value="Input value 10" /></td>
    </tr>
</table>

into this code:

<table>
    <tr>
        <td>Input value 1</td>
        <td>Input value 2</td>
        ...
        <td>Input value 10</td>
    </tr>
</table>

Thanks.

4
  • Yes it can. What errors are you getting with the code you have written? Commented Jan 8, 2012 at 15:33
  • @RoryMcCrossan: I haven't written any code yet, I'm kind of new to jQuery. Commented Jan 8, 2012 at 15:34
  • Try to narrow down your question. Are you screen scraping another website, are you trying to change your own? What attempts have you made? Commented Jan 8, 2012 at 15:37
  • The answer you've accepted (boobiq's) has a pretty big issue, see scessor's answer for a (much) better solution. See my comment on that answer for details. Commented Jan 8, 2012 at 23:37

3 Answers 3

3
$('td').each(function() {
    $(this).text($(this).find('input').val());
});

Also see this example.

Sign up to request clarification or add additional context in comments.

2 Comments

@T.J.Crowder - I suppose it's not possible that interpreting the HTML instead of encoding it as text may be desirable? I can see the logic of $.text(), but I don't think $.html() is inherently wrong.
@JaredFarrish: See my comment on boobiq's answer.
1
$('td').each(function(){
  var elem = $(this);
  elem.text(elem.find('input[type="text"]').val());
});

Comments

0

in this case, you can use for example:

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

untested, but that should be enough

13 Comments

...and if the value contains HTML special characters?
While this works, scessor's answer has much better performance, and does not have the problem of having to encode HTML characters.
@RoryMcCrossan - The issue that matters is performance; the special characters IMO is somewhat of a red-herring. $.text() I assume would have better performance for larger tables. The best answer would specify that $.html() should be used if markup should be interpreted, otherwise use $.text().
@JaredFarrish: Completely disagree that the special characters are a red herring. That's how we get exploits and security holes. What if I put <script src="destroy.js"></script> in a text field and this code is run? What then? We have the tools to prevent that attack vector, why in heaven's name would we not use them?
@JaredFarrish: LOL!! ;-) I can't even deny it. Blast.
|

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.