使用jQuery,这是一种方法:
HTML:
?<form name='theform' id='theform' action=''>
<textarea id='nonumbers' cols='60' rows='10'> </textarea>
</form>????????????????????????????????????????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)
JavaScript的:
$().ready(function(){
$("textarea#nonumbers").keyup(removeextra).blur(removeextra);
});
function removeextra() {
var initVal = $(this).val();
outputVal = initVal.replace(/[^0-9a-zA-Z]/g,"");
if (initVal != outputVal) {
$(this).val(outputVal);
}
};
Run Code Online (Sandbox Code Playgroud)
编辑:正如在评论中所说,原始(使用.keyup()事件)将通过鼠标上下文菜单打开粘贴的可能性,所以我添加了一个.blur()事件..change()本来也是可能的,但有报道称有懈怠.另一种选择是使用.focusout().是时候试验......