jquery append row onclick
**EDIT --- Trying an even more simplified version.... Still doesn't work... Returns $(this).closest is not a function error... **
$("#fitable input[name^=f1]").focus(function() {
var newRow = '<tr><td></td><td></td><td></td><td></td></tr>';
$(this).closest("tbody").appe开发者_StackOverflownd(newRow);
});
Original Post
Pretty new to jQuery, so I'm hoping someone can help me out... There's a couple of things going on here... Help with any part of it is appreciated.
For starters, I'm trying to append a row to a table when a user clicks in the first enabled input field for that row. Here's the code I'm trying to use:
$("#fitable > tbody > tr > td > input").bind('focus', function() {
if($(this).attr('disabled', false)) {
$(this).click(function() {
var newRow = '<tr><td><input name="f1[]" value="" /><label>CustNew</label></td><td><input name="field_n1[]" value="" /><label>N1</label></td><td><input name="field_n2[]" value="" /><label>N2</label></td></tr>';
$(this).closest("tbody").append(newRow);
});
}
});
If it's helpful, here's the html:
<table id="fitable">
<tbody>
<tr valign="top">
<td><input disabled="disabled" name="cust" id="edit-cust" value="sample@sample.com" type="text"><label>Cust</label></td>
<td><input name="field_n1[]" value="" type="text"><label>N1</label></td>
<td><input name="field_n2[]" value="" type="text"><label>N2</label></td>
</tr>
</tbody>
</table>
I think your if statement is setting the clicked attribute to false. Try this:
if( $( this ).attr( 'disabled' ) == false ) {
// do stuff
}
I think your selector is incorrect. Try this:
$("#fitable > tr td input:enabled:first").focus(function() {
var newRow = '<tr><td><input name="f1[]" value="" /><label>CustNew</label></td><td><input name="field_n1[]" value="" /><label>N1</label></td><td><input name="field_n2[]" value="" /><label>N2</label></td></tr>';
$(this).parents("tbody:first").append(newRow);
});
You don't have to check disabled in the handler function, because this will only bind to the enabled elements in the first place.
Try this:
$("#fitable input").focus(function() {
if($(this).attr('disabled', false)) {
$(this).click(function() {
var newRow = '<tr><td><input name="f1[]" value="" /><label>CustNew</label></td><td><input name="field_n1[]" value="" /><label>N1</label></td><td><input name="field_n2[]" value="" /><label>N2</label></td></tr>';
$(this).closest("tbody").append(newRow);
});
}
});
精彩评论