Javascript – Issues using onchange() and onkeypress() together

htmljavascriptjquery

I have an input that needs to be a numerical digit and needs to update a label when the value is changed.

<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)">

The onkeypress function is needed to ensure that the user can only enter in numbers, and the onchange will update my label with the new information.

The onkeypress function is working great, I am only able to type numbers. However, the onchange function is doing nothing.

validation function:

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;};

Update Function:

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

Best Solution

Since you're using jQuery, you might as well use the jQuery event handlers as well:

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");
});

Working example: http://jsfiddle.net/charlescarver/e43pE/1/

Does this suit your needs? Or are you needing to keep this.update_shares = function(o)?