如何在按键上获取输入的新值?
我收到了以下代码:
checkfield = function(evt, textfield) {
var newValue = \*put new value here*\;
var myRegex = \*regex here*\
if(!myRegex.test(newValue)) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
我无法使用keyup或keydown事件,因为preventDefault
不起作用。
我可以用textfield.value
读取未更改的值,我可以使用
var theEvent = evt || window.event;
var key = theEvent.which;
key = String.fromCharCode( key );
以正确的方式将两者结合起来应该不会太难,但我不知道在不禁用preventDefault
答案 0 :(得分:1)
我得到了以下答案,可能不是最好的答案,但它有效:
checkfield = function(evt, textfield) {
var newValue = \*put new value here*\;
var myRegex = \*regex here*\
if(textfield.selectionStart === textfield.selectionEnd) {
var caretPosition = textfield.selectionStart;
var stringPart1 = textfield.value.substring(0, caretPosition);
var stringPart2 = textfield.value.substring(caretPosition, textfield.value.length);
newValue = stringPart1 + key + stringPart2;
} else {
var selectionStart = textfield.selectionStart;
var selectionEnd = textfield.selectionEnd;
var stringPart1 = textfield.value.substring(0, selectionStart);
var stringPart2 = textfield.value.substring(selectionEnd, textfield.value.length);
newValue = stringPart1 + key + stringPart2;
console.log(newText);
}
if(!myRegex.test(newValue)) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
if(!myRegex.test(newValue)) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}