Reputation: 69
I want to delete the character typed in the text box if it is not a number or decimal point in key press event. but I can not do this in the code that handle key press event because the character is displayed after key press event. please tell me how can I do this ?
span = document.createElement("span");
var txt1=($('<input>').attr('type', 'text').attr('id', 'id1').appendTo(span));
txt1.bind("keypress", function () {
if (!validatedText(txt1.attr('id'), event)){
removeCharEntered(txt1.attr('id'));
}
});
var validatedText = function (id, event) {
var text=$('#' + id).val();
var len = text.length;
var ch = event.charCode;
//check for numbers
if (ch != 46) {
if ((ch < 48) || (ch > 57)) {
alert('please enter numbers only.');
return false;
}
}
//check for more than one decimal point
else
for (var i = 0; i < len; i++) {
if (text.charAt(i) == '.'){
alert('please enter numbers only.');
return false;
}
}
return true;
};
//attempting to delete the typed character but failed
var removeCharEntered = function (id) {
var text = $('#' + id).val();
var len = text.length;
$('#' + id).val(text.substr(0,len - 1));
}
Upvotes: 1
Views: 1547
Reputation: 69
by using event.preventDefault() function my problem is solved.
Upvotes: 1