Reputation: 13166
I have a web application that has set to navigate its input fields using Enter key too. In addition, I have a control in my forms that appends new rows to a table that contains my input fields.
<select name="more" id="more" style="width:50px">
<option value="0">0</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
</select>
And this what I used for appending new rows containing input fields.
$('#more').change(function(e) {
var current_rows = ($('#myTable tr').length)-1;
current_rows = parseInt(current_rows);
var more = $('#more').val();
more = parseInt(more);
if (more != '0') {
for (i = current_rows+1 ; i <= current_rows+more ; i++) {
// rows HTML tags here as content
$('#myTable tr:last').after(content);
}
}
$('#more').val('0');
});
Imagine that I have 5 rows at the first time. Whenever I press Enter, the cursor changes its position from the current field to the next one. But when I append new rows and their input fields, anything will not happen from the 6th row. Even, it can not fetch the key code for the Enter using my previous code.
if (event.keyCode == 13) {
// do something
}
What is the matter ?
Upvotes: 2
Views: 1526
Reputation: 13166
Finally I could solve my problem using Ali's and mrtsherman's suggestions.
$("#myTable").delegate("input","keypress",function(e) {
// do something
})
Thank you Ali and Mrtsherman.
Upvotes: 0
Reputation: 39872
If you are in jQuery 1.7+ then use on
or delegate
instead. It is more efficient than old methods. Here I monitor the table for click events on table cells. When an event occurs I add clicked!
to the table cell. This works for both the initial table cells and added ones.
$('#more').change(function(e) {
for (var i = 0; i < $(this).val(); i++) {
$('#myTable').append('<tr><td></td></tr>');
}
});
$('table').on('click', 'td', function() {
$(this).html('clicked!');
});
Upvotes: 2
Reputation: 4599
I think it is because you load other rows dynamically into you DOM .Maybe the "Live" method of Jquery can help you
$("#myTable tr").live("keypress",function (e){
if(e.keyCode == 13)
//Do somthing
});
if this solution did not work , comment me to edit it
Good luck, Ali
Upvotes: 0