TTT
TTT

Reputation: 4434

Jquery insert an image to a HTML table

I want to use jQuery to insert an image after a certain row of a HTML table. I tried to use the appendTo function, but it did not work. I guess its something wrong with my jQuery selector. Can anyone correct my code?

Thanks!

HTML code:

<div class="articles">
<table align="center">
<tr><th><label for="id_chemical_name">Chemical name:</label></th><td><textarea id="id_chemical_name" rows="2" cols="17" name="chemical_name">Spinosad</textarea></td></tr>
<tr><th><label for="id_T">Number of time intervals:</label></th><td><input type="text" name="T" value="10" id="id_T" /></td></tr>

<!--I would like to insert an image after the row 'Number of time intervals'-->

<tr><th><label for="id_a">Logistic model parameter (&#945;):</label></th><td><input type="text" name="a" value="0.746" id="id_a" /></td></tr>
</table></div>

jQuery code:

<script type="text/javascript" src=" ../stylesheets/jquery-1.7.2.js"></script> 
<script>
    $(document).ready(function(){ 
    $('<img src = "https://www.google.com/images/srpr/logo3w.png" />').appendTo('#id_T');
})
</script>

Here is a demo of the question.

Upvotes: 2

Views: 6082

Answers (5)

Silver Gonzales
Silver Gonzales

Reputation: 734

You cannot insert an image directly to a table without enclosing it in a tr and td/th element. I think this is what you are trying to do:

$('<tr><th colspan="2"><img src = "https://www.google.com/images/srpr/logo3w.png" /></th></tr>').insertAfter($("#id_T").parent("td").parent("tr"));

Upvotes: 1

user1350140
user1350140

Reputation:

Any table's content should be inside td or th tag which should be in valid tr tag. Check your selector place again.

Upvotes: 0

Jo&#227;o Mosmann
Jo&#227;o Mosmann

Reputation: 2902

To add a image to the same TD that id_T is in. Do that

$('<img src = "https://www.google.com/images/srpr/logo3w.png" />').appendTo($('#id_T').parent());

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

#id_T is a text input, you can't append an image to it.

Why can't you just put the image in manually? Especially since you can't just dump an image in the middle of a table structure like that.

Upvotes: 0

Rex M
Rex M

Reputation: 144112

The element with ID id_T is an <input> - specifically a textbox - which cannot have child elements (and certainly not a child image).

You may want to try insertBefore or insertAfter instead, or you could use something like:

$('#id_T').closest('td').appendTo...

to move up the DOM from the input and find the containing <td>.

Upvotes: 0

Related Questions