Add New Row To Table Using JQuery On Enter Key Button
I need to add a new to the HTML when the user enters something in the 'Other' text box. I'm using the below HTML, JavaScript and CSS code HTML: <trclass="table-row">'+
'<td class="table-cell">' + this.value + '</td>' +
'<td class="table-cell">' +
'<input type="radio" name="yes" />' +
'</td>' +
'<td class="table-cell">' +
'<input type="radio" name="yes" />' +
'</td></tr>');
}
});
Solution 2:
Use last()
and after()
to append a new row after the last one:
var new_cell_name = $('#your_other_input_field').val();
$('.table-row').last().after('<tr class="table_row">'
+ '<td class="table-cell">' + new_cell_name + '</td>'
+ '<td class="table-cell"><input type="text" name="yes"></td>'
+ '</tr>');
Notes: you should change the names of your text boxes to either a unique name or use an array like name="yes[]"
to avoid naming conflicts.
EDIT
Just noticed you want to remove the other row and add the new one, so use replaceWith()
instead:
$('.table-row').last().replaceWith('
Docs:
Solution 3:
You can add a row like this:
$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');
You can check if the textbox contains text or is empty with:
var inp = $("#txt");
// where #txt is the id of the textbox
if (inp.val().length > 0) {
// do something
}
You can detect enter
press on keyboard with:
$(".table-cell-text").keyup(function (event) {
if (event.keyCode == 13) {
alert('You pressed enter');
}
});
Combining these, you get something like this:
jQuery
var inp = $("#txt");
// where #txt is the id of the textbox
$(".table-cell-text").keyup(function (event) {
if (event.keyCode == 13) {
if (inp.val().length > 0) {
$('#myTable tr:last').before('<tr class="table-row"><td class="table-cell">' + inp.val() + '</td>' +
'<td class="table-cell">' +
'<input type="radio" name="yes" />' +
'</td>' +
'<td class="table-cell">' +
'<input type="radio" name="yes" />' +
'</td></tr>');
}
}
});
Where you change <table>
in your HTML to e.g. <table id="myTable">
HTML
<table id="myTable">
<tr class="table-header">
<td class="table-cell">Game</td>
<td class="table-cell">Yes </td>
<td class="table-cell">No</td>
</tr>
<tr class="table-row">
<td class="table-cell">
FootBall
</td>
<td class="table-cell">
<input type="radio" name="yes">
</td>
<td class="table-cell">
<input type="radio" name="yes">
</td>
</tr>
<tr class="table-row">
<td class="table-cell">
Hockey
</td>
<td class="table-cell">
<input type="radio" name="yes">
</td>
<td class="table-cell">
<input type="radio" name="yes">
</td>
</tr>
<tr class="table-row">
<td class="table-cell">
Other
</td>
<td class="table-cell-text">
<input type="text" name="yes" id="txt">
</td>
</tr>
</table>
I didn't run the code yet, so beware of any typos. Hope that helps you out.
You can find a jsFiddle
HERE.
If you want the 'other' tr
to disappear, you can use .replaceWith()
instead of .before()
Post a Comment for "Add New Row To Table Using JQuery On Enter Key Button"