如果它不是按键事件中的数字或小数点,我想删除在文本框中键入的字符。但我不能在处理按键事件的代码中执行此操作,因为在按键事件后显示该字符。请告诉我怎么做?
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));
}
答案 0 :(得分:1)
通过使用event.preventDefault()函数解决了我的问题。