2014-04-21 27 views
0

我有一個表,其中文本框動態生成。每行只有一個文本框。所有文本框具有相同的類(qt)和表格單元格有一個類(數量)。我想綁定一個按鍵事件,以便只有數字可以輸入到目前爲止我已編碼了一下,如下所示請幫助。我如何將按鍵事件綁定到具有相同類的文本框

$("#qt").keypress(function(e) { 
     //if the letter is not digit then display error and don't type anything 
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { 

      return false; 
     } 
    }); 

回答

1

你應該使用event delegation因爲元素是動態創建

$(document).on("keypress", ".qty", function (e) { 
//if the letter is not digit then display error and don't type anything 
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { 

     return false; 
    } 

}); 

事件委派,您可以附加一個事件偵聽器,以父元素,這將觸發對所有選擇匹配的孩子,無論這些孩子現在是存在還是未來增加。

+1

您的回答正確,但代替qty它應該是qt – user3555417

0

使用jQuery,你可以這樣做:

$(document).on('keypress','.qt',function(e) { 
     //if the letter is not digit then display error and don't type anything 
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { 

      return false; 
     } 
    }); 

Fiddle DEMO using jquery 1.10.1

0

使用.指定類,而不是# - 用於標識。由於文本框是動態生成的,因此您需要使用事件代理:

$("#tableID").on('keypress', ".qt", function(e) { 
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { 
     return false; 
    } 
}); 
相關問題