append new rows and input tags using jQuery

不羁的心 提交于 2019-12-11 03:44:16

问题


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 ?


回答1:


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.

http://jsfiddle.net/WBxQz/1/

$('#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!');
});



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/8543135/append-new-rows-and-input-tags-using-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!