[英]javascript onChange computation - show only one alert
我不知道如何正確地命名我的問題,但是這里有。
在我的html中,我有一個“表單”,但沒有
<form></form>
只需幾個選擇,單選按鈕和文本輸入即可。 我輸入,檢查和選擇值,然后根據這些值進行一些計算。 這種“形式”是在每次擊鍵,模糊,變化時計算的。 因此,當我更改一個值時,它將立即使用新值重新計算結果。
我想提醒用戶,當他沒有填寫任何必要的信息時。 現在是這樣工作的(在一個單獨的.js文件中)
function calculator() {
// Here is code that gathers the data from html
// and here are also some computations (many if-s)
// The code is too long to be putted here
}
$(function () {
$('select, input').on('keydown blur change', calculator);
});
我試圖將if語句放入計算器函數中:
function calculator() {
// Here is code that gathers the data from html
// and here are also some computations (many if-s)
// The code is too long to be putted here
if (val1 == '' && sadzba == '' && viem == '' && ...) {
alert('You have to fill all necessary fields!')
}
}
顯然,這導致每次我輸入/選擇新值時都會彈出警報,因為一開始所有變量都是空的/沒有任何值。 因此,如何實現這種情況:用戶填寫(例如)一個值以外的“表單”,然后才會彈出警報。
比你。
我建議對提交進行檢查,如果其中一個字段為空,則返回false ,以防止提交表單。
$('form').on('submit', function () {
if (val1 == '' || sadzba == '' || viem == '') {
alert('You have to fill all necessary fields!');
return false;
} else { return true; }
});
為onblur
事件使用其他事件處理程序,因為那是當光標離開輸入框時。 (它還可以防止事件處理程序始終觸發。這是一個非常昂貴的過程,它可能會降低頁面速度)
$('select, input').on('blur', didTheyLeaveTheFieldEmpty);
希望我理解正確,您可以嘗試以下方法:
function calculator(event) {
if ( $(event.target).val().length == 0 ) {
alert('fill the field');
}
}
$('select, input').on('keyup', calculator);
即使您不希望帶有提交按鈕的表單,也可以創建一個按鈕並在單擊時觸發代碼
<input type="button" class="calculate">
$(function () {
$('.calculate').on('click', calculator);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.