Joseph
Joseph

Reputation: 692

keypress event not working with addEventListener Function

I have an input field with ID mobileNumber , it takes only numbers as input so, i have written a function(event handler function) which checks the input. But if you add the function via the addEventListener function it won't work, but if you add via onkeypress attribute it works..

e.g.

<input type="text" class="insidetxt" placeholder="Mobile Number" name="mobile number" id="mobileNumber">

 //input field;

 var isNumeric =function (event){
     var specialKeys = new Array();
        specialKeys.push(8); //Backspace
        var keyCode = event.which ? event.which : event.keyCode
        var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);  
        return ret;
  }; 

  //this function check whether the input character is digit or not


 eventObj["isNumeric"] = function (event){
     var specialKeys = new Array();
        specialKeys.push(8); //Backspace
        var keyCode = event.which ? event.which : event.keyCode
        var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);  
        return ret;
  }; 

//event obj contains the function to check, same functionality 

(function(eventObj){
  var mobileInput =  document.getElementById("mobileNumber");
  mobileInput.addEventListener("keypress", eventObj["isNumeric"], false);
})(eventObj);

If I add the event listener like this the function is called but doesn't restrict the user from entering the characters also;

but if I do like this:

<input type="text" class="insidetxt" placeholder="Mobile Number" name="mobile number" id="mobileNumber" onkeypress="return isNumeric(event); ">

this works fine

Am I doing something wrong in the second way?

Upvotes: 0

Views: 748

Answers (2)

Joseph
Joseph

Reputation: 692

got the solution,.. need to prevent the defaultBehaviour when the ret variable is false

eventObj["isNumeric"] = function(event) {

 var specialKeys = new Array();
    specialKeys.push(8); //Backspace
    var keyCode = event.which ? event.which : event.keyCode
    var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);  
    if(!ret)
        event.preventDefault();

};

Upvotes: 1

partha
partha

Reputation: 1

Yeah, the second approach is not a best practice. Html attribute can be changed or bypassed, so it is better to add event listeners.

Upvotes: 0

Related Questions