Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery insert new element into table cell without erasing other elements

Tags:

jquery

A table contains several rows, each with four cells.

In a cell with id=tdJane, I already have two input elements:

<table>
    <tr>
        <td id="tdBob">
            <input type="hidden" id="hida" value="some stuff">
            <input type="hidden" id="hidb" value="other stuff">
        <td>
        <td id="tdJane">
            <input type="hidden" id="hid1" value="some text">
            <input type="hidden" id="hid2" value="other text">
        <td>
    </tr>
</table>

Into cell #tdJane, I wish to insert a new hidden input field below #hid2

I tried this:

$('#tdJane').html('<input type="hidden" id="hid3" value="newest text">') 

but that overwrites the existing contents of the cell.

How can I do it?

like image 755
cssyphus Avatar asked Sep 01 '26 14:09

cssyphus


1 Answers

You need to use .append(), .html() will overwrite the contents.

$('#tdJane').append('<input type="hidden" id="hid3" value="newest text">');

You can use jquery element constructor for more clarity.

 $('#tdJane').append($('<input/>',{type:'hidden',
                                   id: 'hid3',
                                   value:'newest text'}));

See viewsource in this Demo

like image 148
PSL Avatar answered Sep 03 '26 05:09

PSL