[英]I have a windows onload function for onclick How can I add an onblur event and combine into one?
[英]How can I call to HTML DOM Event Object (for example: onclick, onblur, etc..) nested functions?
美好的一天! 假設我的頁面中有一組文本字段,每個文本字段在onblur期間都有自己的驗證,例如,數量文本字段。如果我刪除焦點,它將檢查它是否大於100,000。
<input type = "text" id = "amount" placeholder="Amount" onblur="validateAmount()">
function validateAmount(){
var amount = document.getElementById("amount").value;
if (amount > 100000){
document.getElementById("errormessage").innerHTML = "Invalid! Enter a number less than 100,000!"; //Let's just assume that I have a label for the error message
}
}
糟糕! 這只是具有驗證的文本字段之一,如果我有5個,我們假設單擊按鈕以處理驗證中存在3個問題的數據,因此由於這些錯誤,將不會處理數據。 在我的情況下,我將使用onclick事件,請看以下示例:
<button onclick = "checkData()"> Apply </button>
function checkData(){
//Here in checkData() method/function, I want to put the validateAmount() function above and other functions of validation during onblur to count and state the number of errors before submitting the data.
var numberOfErrors = 0;
function validateAmount(){
var amount = document.getElementById("amount").value;
if (amount > 100000){
document.getElementById("errormessage").innerHTML = "Invalid! Enter a number less than 100,000!"; //Let's just assume that I have a label for the error message
numberOfErrors++;
}
}
/* And more validating functions here
*/
// After validating all the textfields.
if(numberOfErrors == 0){
alert("Congrats! You already submitted the loan");
} else {
alert("Error! Check your inputs!");
}
}
所以我的問題是,如何在HTML DOM事件的函數內部調用函數? 有沒有可能更簡單的方法來做到這一點? 先感謝您!
有很多解決方法,但是我建議使用驗證庫。 自己動手是一個非常冒險的提議,並且會導致難以管理的“意大利面條代碼”。
您可以查看以下兩個庫。
您可以將“ this”傳遞給事件處理程序,以便它知道應該驗證哪個字段。 提交表單時,我會再次運行所有驗證功能,而不是保留一個計數,因為如果人們更正錯誤或將錯誤添加到先前更正的字段中,這可能會變得混亂。
我添加了一個虛擬驗證器作為示例。
function checkData(field){ if (!field){ var numberOfErrors = 0; if (!validateAmount()) numberOfErrors++; if (!validateOther()) numberOfErrors++; if (!numberOfErrors){ alert("Congrats! You already submitted the loan"); } else { alert("Error! Check your inputs!"); } } else if (field.id == "amount") validateAmount() else if (field.id == "other") validateOther(); function validateAmount(){ var amount = parseFloat(document.getElementById("amount").value); if (isNaN(amount) || amount > 100000){ document.getElementById("errormessage").innerHTML = "Invalid! Amount must be less than 100,000!"; return(false); } return(true); } function validateOther(){ var other = parseFloat(document.getElementById("other").value); if (isNaN(other) || other > 100){ document.getElementById("errormessage").innerHTML = "Invalid! Other must be less than 100!"; return(false); } return(true); } }
<form> <input type = "text" id = "amount" placeholder="Amount" onblur="checkData(this);"> <input type = "text" id = "other" placeholder="Other" onblur="checkData(this);"> <button onclick = "checkData()"> Apply </button> </form> <div id="errormessage"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.