Reputation: 17
im new to jquery and im trying to create elements on a button click and set attributes to it. here is my code so far
$('#myTable').append(
$('<tr>').append(
$('<td>').append(
$('<input>', {type: 'text', id: 'id'}).append(
$('<td>').append(
$('<input>', {type: 'button', id: 'btnAdd', onclick: 'AddRow()',value: 'addrow'})
)
)
)
)
);
i know this is wrong so i need your help to fix it.
what i'd like to output is:
<tr>
<td><input type="text" id="id"></td>
<td><input type="button" id="btnAdd" onclick="AddRow()" value="addrow"></td>
</tr>
Upvotes: 1
Views: 151
Reputation: 228
$(document).ready(function() {
var html_obj = '<tr>';
html_obj += '<td> <input type="text" id="id" value=""/> </td>';
html_obj += '<td> <input type="button" id="btnAdd" onclick="AddRow()"
value="addrow" /> </td>';
html_obj += '</tr>';
$('#myTable').append(html_obj);
});
<table id="myTable">
</table>
If you have a empty table else you can use the $('#myTable tr:last').after(html_obj). this is will give you a perfect structure. Hope this will work.
Upvotes: 0
Reputation: 562
Use the jQuery.attr function to set the html attributes of the elements:
Edit: There was also a logic error.
$('#myTable').append(
$('<tr>').append(
$('<td>').append(
$('<input>' )
.attr( {type: 'text', id: 'id'} )
)
)
.append(
$('<td>').append(
$('<input>' )
.attr( {type: 'button', id: 'btnAdd', onclick: 'AddRow()',value: 'addrow'} )
)
)
);
See also: http://api.jquery.com/attr/
Upvotes: 1
Reputation: 17550
You can simply write
$('#myTable').append('<tr><td><input type="text" id="id"></td><td><input type="button" id="btnAdd" onclick="AddRow()" value="addrow"></td></tr>');
Upvotes: 5