我試圖在前端用javascript來驗證我的woocommerce結帳表單。驗證正確執行,但問題是在第一個.remove()陳述句后函式就退出了。
我想在第一個remove()條件執行后,也執行第二個、第三個remove()條件(我是說所有的remove條件都應該運行)。 誰能幫幫我? 附上下面的代碼。
function myFunction() {
//為名稱
let n = document.getElementById("billing_first_name").value。
if ( n.length < 3 || n == ' ' ) {
var n1 = document.getElementById('billing_first_name') 。
if(!document.getElementById("sp_billing_first_name_field")){
n1.insertAdjacentHTML('afterend', '<p class="sp-error-notice" id="sp_billing_first_name_field"> This is test< /p> ')。
}
}
else {
document.getElementById('sp_billing_first_name_field').remove() 。
}
//姓氏。
let n2 = document.getElementById("billing_last_name"/span>).value。
if ( n2.length < 3 || n2 == ' ' ) {
var n21 = document.getElementById('billing_last_name') 。
if(!document.getElementById("sp_billing_last_name_field")){
n21. insertAdjacentHTML('afterend', '< p class="sp-error-notice" id="sp_billing_last_name_field">お名前(姓?名)は必ず入力してください。</p>')。)
}
}
else {
document.getElementById('sp_billing_last_name_field').remove()。
}
uj5u.com熱心網友回復:
你的主要問題是,你試圖洗掉一個元素而不檢查它是否存在。
document.getElementById('sp_billing_last_name_field').remove()。
當sp_billing_last_name_field不存在時,會出現錯誤。這樣會更好:
let hint = document.getElementById('sp_billing_last_name_field') 。
if (hint) hint.remove();
但是你也有代碼重復的問題。讓我們做一個可以檢查任何輸入欄位并顯示資訊的函式:
。function checkField(fieldId, condition, message) {
document.getElementById(fieldId)。 addEventListener("input", function () {
let isInvalid = condition(this.value) 。
let hint = this.nextElementSibling。
if (hint && !hint.classList。 contains("sp-error-notice")) hint = null;
if (!hint && isInvalid) {
this. insertAdjacentHTML('afterend', '<p class="sp-error-notice"> ' message '</p> ')。
} else if (hint & & !isInvalid) {
hint.remove()。
}
});
}
checkField("billing_first_name", v => /span> v. length < 3, "ダメよ")。)
checkField("billing_last_name", v => v。 length < 3, "お名前(姓?名)は必ず入力してください。");
p.sp-error-notice{
display: inline-block;
color: red; margin: 0 0 0 10px;
}
<div>< input id="billing_first_name"></div>>
<div>< input id="billing_last_name"><
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/310000.html
標籤:
上一篇:在for回圈中的and運算子和or運算子之間有什么區別?
下一篇:在點擊事件中改變選定的標簽
