Reputation: 183
I need to add dynamically a row in jquery, this is my code:
var row = $('<tr />')
.append($('<td />'))
.append($('<td>' + response.nome + '</td>'))
.append($('<td />', {
style: "text-align:center"
}).append($('<input />', {
type: 'image',
src: 'nienteico.png',
'class': 'ajaxEdit',
id: '1.' + response.row_id
}).css({
cursor: 'pointer',
width: '40px',
height: '40px',
}).click(function() {
cambiastato('1.' + response.row_id);
})));
In particular, as regards the last element i'm expecting to get 'id' attribute and one 'onclick function'. Something like:
<tr>
<td></td>
<td>uytredsgfh</td>
<td style="text-align:center">
<input type="image" src="nienteico.png" style="cursor:pointer; width:40px; height:40px" id="1.15" class="ajaxEdit" onclick="cambiastato(1.15)">
</td>
</tr>
The first two elements are correctly written, but unfortunally this is what i get for the last one (id attribute and onclick function missed!)
<td style="text-align:center">
<input type="image" src="nienteico.png" class="ajaxEdit" style="cursor: pointer; width: 40px; height: 40px;">
</td>
Any help or suggestions? Thanks
Upvotes: 0
Views: 31
Reputation: 16609
This is what you would expect.
Your id
is invalid because it starts with a number - see w3.org. jQuery is probably rejecting it because of this.
The click event is not written as an attribute of the tag. Instead it is hooked up as a property of the DOM element the tag represents. You will probably find that it works if you put the input
on the page and click it.
If you do want to explicitly output the onclick
and other attributes into the tag, you can just set them in the initial tag creation call:
var row = $('<tr />')
.append($('<td />'))
.append($('<td>' + response.nome + '</td>'))
.append($('<td style="text-align:center" />')
.append($('<input onclick="cambiastato(1.' + response.row_id + ');" type="image" src="nienteico.png" class="ajaxEdit" id="1.' + response.row_id + '" />')
.css({
cursor: 'pointer',
width: '40px',
height: '40px',
})
));
Upvotes: 1
Reputation: 3780
Your code is correct. jQuery is not adding attributes to the element it is adding an Event Listener to the DOM. In other words it will not show up in the markup even when it is working. Try adding a console.log
statement to the listener and trying it out - it should work.
On a side note there are a few best practices that might help keep your code cleaner and more maintainable.
$
to prefix variable names. In your example this would be $row
.$input
element into it's own variable.Best of luck!
Upvotes: 1