2013-05-05 58 views
4

我有一個輸入需要是數字數字,並且需要在值更改時更新標籤。使用onchange()和onkeypress()一起使用的問題

<input id="shares" name="shares" type="text" maxlength="3" onchange="game_board.update_shares(this);this.oldvalue = this.value;" onkeypress="return game_board.isNumberKey(event)"> 

需要onkeypress函數來確保用戶只能輸入數字,onchange會用新信息更新我的標籤。

onkeypress函數工作得很好,我只能輸入數字。但是,onchange函數什麼都不做。

驗證功能:

this.isNumberKey = function(evt){ 
var charCode = (evt.which) ? evt.which : event.keyCode; 
if (charCode != 46 && charCode > 31 
    && (charCode < 48 || charCode > 57)){ 
    return false; 
    } 

return true;}; 

更新功能:

this.update_shares = function(o){ 
alert("test"); 
$(".dollar_amount").html("$" + "value" + ".00");}; 
+0

jQuery將完成所有需要*翻譯*,'evt.which'就夠了。 – 2013-05-05 19:03:09

回答

3

由於您使用jQuery,你還不如用jQuery的事件處理程序,以及:

HTML

<input id="shares" name="shares" type="text" maxlength="3" /> 
<div class="dollar_amount"></div> 

JS

$("#shares").on("keydown", function (evt) { 
    var charCode = (evt.which) ? evt.which : event.keyCode; 
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) { 
     return false; 
    } 
    return true; 
}); 

$("#shares").on("change", function() { 
    var o = $(this).val(); 
    $(".dollar_amount").html("$" + o + ".00"); 
}); 

工作例如:http://jsfiddle.net/charlescarver/e43pE/1/

這是否滿足您的需求?或者你需要保持this.update_shares = function(o)

+0

哇,看起來像Jquery比我想象的還多。大聲笑 謝謝你。 – gamesfreke 2013-05-05 19:32:22

+0

好的,我錯過了一些東西。如果這段代碼在外部文件中工作,它應該有什麼不同?我不這麼認爲,但現在這兩種功能都不起作用。 此外,這可能或可能不重要,「.dollar_amount」是在一個對話框中。 – gamesfreke 2013-05-05 19:43:28

+0

因爲它是jQuery,所以你需要把這個代碼放在'$(document).ready()'函數中。因此,如果它位於外部文件中,請首先在上述代碼之前包含jQuery文件,然後將上面的代碼包含在'$(document).ready()'中。 – Charlie 2013-05-05 19:45:12

2

因此,你想要的是隨着值的變化更新標籤。如果我是你,我會在按鍵事件上做。我的意思是,類似於:

this.isNumberKey = function(evt){ 
    var charCode = (evt.which) ? evt.which : event.keyCode; 
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)){ 
     return false; 
    } 
    $(".dollar_amount").html("$" + "value" + ".00");}; 
    return true; 
}; 
+0

問題是我需要更新與驗證不同。感謝您的幫助。 – gamesfreke 2013-05-05 19:27:28

+0

確實老兄,沒問題;) – 2013-05-05 23:21:21

相關問題