我有一個ID爲#primarySearch
的表單。它有3個文本輸入,全部都有自己的ID,如下所示:#ecNumber
,#casNumber
,#substanceName
。jquery裏面運行條件驗證.on
我有以下js。如果用戶輸入在#primarySearch
文本輸入什麼它運行一個名爲processPrimarySearch
功能和適當的輸入值發送給它:
$('#primarySearch input[type="text"]').on({
"keyup": function(e) {
// Ignore tab key
if (e.which != 9) {
processPrimarySearch.call(this);
}
}
});
function processPrimarySearch() {
// ...
}
我也得到了一些其他的JS(這只是內部document.ready
)停靠用戶輸入除數字和破折號之外的任何內容 - 但僅限於#ecNumber
和#casNumber
字段(請注意,我從jQuery only allow numbers,letters and hyphens改編了此字段)。雖然此代碼在用戶輸入這兩個字段時觸發,但也會導致processPrimarySearch
運行,而不管用戶輸入是否有效。這是因爲在代碼之間沒有連接之上,下面的代碼:
$('#ecNumber, #casNumber').keypress(function (e) {
var allowedChars = new RegExp("^[0-9\-]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (allowedChars.test(str)) {
return true;
}
e.preventDefault();
return false;
}).keyup(function() {
// the addition, which will check the value after a keyup (triggered by Ctrl+V)
// We take the same regex as for allowedChars, but we add^after the first bracket : it means "all character BUT these"
var forbiddenChars = new RegExp("[^0-9\-]", 'g');
if (forbiddenChars.test($(this).val())) {
$(this).val($(this).val().replace(forbiddenChars, ''));
}
});
發生了什麼,此刻的結果是,如果一個字符被輸入如#ecNumber
「Z」,確認正則表達式代碼將會觸發並停止輸入中出現的字符「z」 - 好的。但是,processPrimarySearch()
也會觸發,因爲它在.on
內部定義爲#primarySearch
表單中的任何輸入。
我的問題: 我想要做的就是運行驗證的正則表達式我.on
內,但只有當它是#ecNumber
或#casNumber
場(#substanceName
不能在此處驗證)。
我已經設法寫出以下內容,它使用數組來說出用戶輸入的是哪個字段。我在哪裏做console.log是我需要驗證正則表達式發生的地方
$('#primarySearch input[type="text"]').on({
"keyup": function(e) {
// Ignore tab key
if (e.which != 9) {
var arr = ["ecNumber", "casNumber"];
if ($.inArray($(this).attr('id'), arr)!== -1) {
console.log($(this).attr('id'));
}
processPrimarySearch.call(this);
}
}
});
這樣做的最佳方法是什麼?我不確定是否將執行正則表達式的代碼移入函數,然後調用它(使用.call
?)或其他方法?有沒有什麼問題與本質上是異步的?
是'#ecNumber'還是'#casNumber'輸入?如果你特別針對它們,在$('#ecNumber,#casNumber')。on(...)'之前添加另一個('$('#primarySearch')...')。這會導致附加的第一個函數首先運行 – BravoZulu
是的,所有3個字段('#ecNumber,#casNumber,#substanceName')都是文本輸入。我更新了這篇文章,提供了更多有關發生的事情的信息。問題是我發佈的第一個代碼與第二個代碼之間沒有任何關聯,因此'processPrimarySearch'運行時不考慮正則表達式驗證的結果。 – Andy