Reputation: 1485
I am trying to add two events on input field like onkeyup and onchange, the purpose is to avoid longpress of characters other than numbers..as the field is for zipcode. At present only one event is working either keypress/onchange. I am adding my code for refrence any help would be appreciated.
function zipchange(obj, selector){
var code = obj.value;
var isnum = /^\d+$/.test(code);
if(!isnum)
obj.value="";
}//onchange
function autoZip(obj, selector){
var code = obj.value;
if(code.match(/\D/gi))
obj.value = code.replace(/\D/gi,'');
if(code.length>4 && code.indexOf('-')== -1){
var substr = code.substring(4);
substr=substr.replace(/\D/gi,'');
obj.value = code.substring(0,4)+'-'+substr;
}//onkeypress
//html
<input id="pincode" type="text" data-validate="validate[required]" name="address.pinCode" required="true" onkeyup="autoZip(this)" onchange="zipchange(this)" msg="Enter valid zip code" />
Answer:
function autoZip(obj, selector){
var code = obj.value;
if(code.match(/\D/gi))
obj.value = code.replace(/\D/gi,'');
if(code.length>4 && code.indexOf('-')== -1){
var substr = code.substring(4);
substr=substr.replace(/\D/gi,'');
var substr1 = code.substring(0,4);
obj.value = substr1+'-'+substr;
var isnum = /^\d+$/.test(substr1)
if(!isnum)
obj.value="";
}
Hi the above modified function did the trick..thanks for all the enlightned ones who helped me..
Upvotes: 1
Views: 181
Reputation: 4621
Well first of all onchange is triggered when you change the content of the text-box and when you loose focus from input type
Hence there is no use in using onchange event you have to implement your onchange logic in keyup event
Upvotes: 2