从$(document).ready创建的文本输入获取Keypress函数

时间:2017-05-23 09:05:54

标签: javascript jquery html validation keypress

我的JavaScript / JQuery中有一个函数,它在$(document).ready上填充一个表单。

$(document).ready(function build_item_table() {
    for (var x = 1; x <= 20; x++) {
        $('#item_table tbody').append("<tr>");
        $('#item_table tbody').append("<td><select id=\"item_" + x + "_budget\" name=\"item_" + x + "_budget\" class=\"item_budget\" width=\"110px\"><option>Loading...</option></select></td>");
        $('#item_table tbody').append("<td><input type=\"text\" id=\"item_" + x + "_code\" name=\"item_" + x + "_code\" class=\"code_textbox\" size=\"20\"></td>");
        $('#item_table tbody').append("<td><input type=\"text\" id=\"item_" + x + "_description\" name=\"item_" + x + "_description\" class=\"desc_textbox\" size=\"83\"></td>");
        $('#item_table tbody').append("<td><input type=\"text\" id=\"item_" + x + "_quantity\" name=\"item_" + x + "_quantity\" class=\"cost_textbox\" size=\"7\" value=\"0\" required></td>");
        $('#item_table tbody').append("<td>$&nbsp;<input type=\"text\" id=\"item_" + x + "_unit\" name=\"item_ " + x + "_unit\" class=\"qty_textbox\" size=\"10\" value=\"0.00\" required></td>");
        $('#item_table tbody').append("<td>$&nbsp;<input type=\"text\" id=\"item_" + x + "_total\" name=\"item_" + x + "_total\" class=\"cost_textbox\" size=\"10\" value=\"0.00\" required></td>");
        $('#item_table tbody').append("</tr>");
    }
});

但是,我想通过这个函数验证一些文本输入(顺便说一下,我对这个函数没有任何赞誉,因为我在这里从这个伟大的社区中找到它):

$('.cost_textbox').keypress(function(eve) {
  if ((eve.which != 46 || $(this).val().indexOf('.') != -1) && (eve.which < 48 || eve.which > 57) || (eve.which == 46 && $(this).caret().start == 0) ) {
    eve.preventDefault();
  }

// this part is when left part of number is deleted and leaves a . in the leftmost position. For example, 33.25, then 33 is deleted
$('.cost_textbox').keyup(function(eve) {
  if($(this).val().indexOf('.') == 0) {    
    $(this).val($(this).val().substring(1));
  }
 });
});

这适用于HTML代码中生成的输入文本框,但不适用于JavaScript中附加的文本框。我该如何解决?提前谢谢。

1 个答案:

答案 0 :(得分:0)

您需要使用.on('xxx')函数代替.xxx()进行委派: 动态创建的元素不会触发基本事件。您需要将侦听器放在不会更改的父级上。

$('body').on('keypress','.cost_textbox',function(eve) {
  if ((eve.which != 46 || $(this).val().indexOf('.') != -1) && (eve.which < 48 || eve.which > 57) || (eve.which == 46 && $(this).caret().start == 0) ) {
    eve.preventDefault();
  }

// this part is when left part of number is deleted and leaves a . in the leftmost position. For example, 33.25, then 33 is deleted
$('body').on('keyup','.cost_textbox',function(eve) {
  if($(this).val().indexOf('.') == 0) {    
    $(this).val($(this).val().substring(1));
  }
 });
});