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">'+
'<tdclass="table-cell">' + this.value + '</td>' +
'<tdclass="table-cell">' +
'<inputtype="radio"name="yes" />' +
'</td>' +
'<tdclass="table-cell">' +
'<inputtype="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('<trclass="table_row">'
+ '<tdclass="table-cell">' + new_cell_name + '</td>'
+ '<tdclass="table-cell"><inputtype="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 textboxif (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
<tableid="myTable"><trclass="table-header"><tdclass="table-cell">Game</td><tdclass="table-cell">Yes </td><tdclass="table-cell">No</td></tr><trclass="table-row"><tdclass="table-cell">
FootBall
</td><tdclass="table-cell"><inputtype="radio"name="yes"></td><tdclass="table-cell"><inputtype="radio"name="yes"></td></tr><trclass="table-row"><tdclass="table-cell">
Hockey
</td><tdclass="table-cell"><inputtype="radio"name="yes"></td><tdclass="table-cell"><inputtype="radio"name="yes"></td></tr><trclass="table-row"><tdclass="table-cell">
Other
</td><tdclass="table-cell-text"><inputtype="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"