[英]event.preventDefault() working in Chrome, but not in Firefox / IE
[英]event.preventDefault() not working for android chrome
event.preventDefault() 不適用於 Chrome Android 操作系統。 而相同的操作在 chrome IOS 上起作用。我什至使用了 event.stopPropagation()、event.stopImmediatePropagation()。
HTML:
<input class="otherAmount" type="text"id="pVal" name="pVal" onkeydown="validatePaymentToTwoDecimal(this,event);"/>
Java 腳本:
function validatePaymentToTwoDecimal(el, evt) {
if(!$.isNumeric(evt.key)|| evt.key=="."){
evt.preventDefault();
evt.stopPropagation();
evt.stopImmediatePropagation();
return false;
} else {
return true;
}
}
根據對類似問題的回答,您應該能夠執行此操作來過濾輸入:
$("#pVal").on(
"input change paste",
function filterNumericAndDecimal(event) {
var formControl;
formControl = $(event.target);
formControl.val(formControl.val().replace(/[^0-9.]+/g, ""));
});
var pInput;
function filterNumericAndDecimal(event) {
var formControl;
formControl = event.target;
formControl.value = formControl.value.replace(/[^0-9.]+/g, ""));
}
pInput = document.getElementById("pVal");
["input", "change", "paste"].forEach(function (eventName) {
pInput.addEventListener(eventName, filterNumericAndDecimal);
});
這是通過使用正則表達式刪除數字和小數點字符來實現的。
替代解決方案將使用textInput
事件代替
const inpt = getElementById('pVal')
inpt.addEventListener('textInput', evt => {
evt.key = evt.data
if(!$.isNumeric(evt.key)|| evt.key=="."){
evt.preventDefault();
}
})
它適用於 Android Chrome
唯一對我有用的解決方案 Android 過濾輸入字符
keydown
不允許在按鍵事件中捕獲某些字符的輸入。 替代方法是使用input
事件。 我試過了,但插入符號有問題,在某些情況下打字時會跳到錯誤的 position。
我已經這樣解決了:
let input = document.getElementById('input')
function withoutForbiddenChars(str){
return str.replace(/[^\d]+/g, '')
}
function handleInput(event) {
let charsBeforeCaret = input.value.slice(0, input.selectionStart)
let charsAfterCaret = input.value.slice(input.selectionStart)
charsBeforeCaret = withoutForbiddenChars(charsBeforeCaret)
charsAfterCaret = withoutForbiddenChars(charsAfterCaret)
input.value = charsBeforeCaret + charsAfterCaret
let newCaretPos = charsBeforeCaret.length
input.selectionStart = newCaretPos
input.selectionEnd = newCaretPos
}
input.addEventListener('input', handleInput, false)
在 Angular 中,我使用了以下指令的代碼,它可以用作 android 的替代方法來防止默認
@HostListener('input', ['$event'])
public onInput(event) {
let val: string = this.el.nativeElement.value;
const position = this.el.nativeElement.selectionStart;
if(event.data == '.' && val.split('.').length > 2){
//This restricts the additional decimal.
this.el.nativeElement.value = val.slice(0, position-1);
}
//This will add default decimal if not entered manually
if (val.length == 9 && !val.includes('.')) {
this.el.nativeElement.value = val + '.';
}
}
此處提供完整代碼=> https://stackoverflow.com/a/74622576/8323774
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.