[英]How to prevent form submission until form is filled using JavaScript?
如果用戶沒有在文本輸入字段中輸入值,例如姓氏或公司,並且至少沒有選擇一個事件(請記住,用戶並不總是在從上到下的順序)。 這是我無法編輯的 php 文件中的示例代碼。 只必須使用 java 腳本。
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class="item">
<span class="eventTitle">Thomas Bewick and His Apprentices</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="1" data-price="0.00"></span>
</div>
<div class="item">
<span class="eventTitle">Winter Festival @ Discovery Museum</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="12" data-price="0.00"></span>
</div>
</section>
<section id="collection">
<h2>Collection method</h2>
<p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
<p>
Home address - £5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked=""> |
Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
</p>
</section>
<section id="makeBooking">
<h2>Make booking</h2>
Your details
Customer Type: <select name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails">
Forename <input type="text" name="forename">
Surname <input type="text" name="surname">
</div>
<div id="tradeCustDetails" class="custDetails" style="visibility:hidden">
Company Name <input type="text" name="companyName">
</div>
<p style="color: red; font-weight: bold;" id="termsText">I have read and agree to the terms and conditions
<input type="checkbox" name="termsChkbx"></p>
<p><input type="submit" name="submit" value="Book now!" disabled=""></p>
</section>
</form>
HTMLFormElement.elements
動態設置required
屬性: 只需使用HTMLFormElement.elements屬性獲取表單中的所有表單控件(輸入、選擇等),然后使用Array.from()方法獲取HTMLFormControlsCollection的淺拷貝數組,您現在可以循環並使用setAttribute()方法為所有表單控件動態設置required
屬性。
檢查並運行以下代碼片段或打開此JSFiddle鏈接以獲取上述方法的實際示例:
// get the form const form = document.getElementById("bookingForm"); // get the form controls let x = form.elements; // Convert the list of form controls to an array and set the required attribute to each control Array.from(x).forEach(e => { e.setAttribute("required", ""); })
<form id="bookingForm" action="javascript:alert('form submitted');" method="get"> <section id="bookEvents"> <h2>Select Events</h2> <div class="item"> <span class="eventTitle">Thomas Bewick and His Apprentices</span> <span class="eventPrice">0.00</span> <span class="chosen"><input type="checkbox" name="event[]" value="1" data-price="0.00"></span> </div> <div class="item"> <span class="eventTitle">Winter Festival @ Discovery Museum</span> <span class="eventPrice">0.00</span> <span class="chosen"><input type="checkbox" name="event[]" value="12" data-price="0.00"></span> </div> </section> <section id="collection"> <h2>Collection method</h2> <p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p> <p> Home address - £5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked=""> | Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0"> </p> </section> <section id="makeBooking"> <h2>Make booking</h2> Your details Customer Type: <select name="customerType"> <option value="">Customer Type?</option> <option value="ret">Customer</option> <option value="trd">Trade</option> </select> <div id="retCustDetails" class="custDetails"> Forename <input type="text" name="forename"> Surname <input type="text" name="surname"> </div> <div id="tradeCustDetails" class="custDetails" style="visibility:hidden"> Company Name <input type="text" name="companyName"> </div> <p style="color: red; font-weight: bold;" id="termsText">I have read and agree to the terms and conditions <input type="checkbox" name="termsChkbx"></p> <p><input type="submit" name="submit" value="Book now!"></p> </section> </form>
required
: 只需為每個輸入元素添加一個required
屬性,如下所示:
<input type="text" name="forename" required>
<input type="text" name="forename" required>
<select name="customerType" required>
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
1_您可以通過JS向輸入添加required
屬性。 :)
2_我不是專業人士,我能想到的唯一方法是使用 AJAX 和 JQuery。像這樣:
<script>
function echo() {
var name = $("#id");
if (name.val() === "") {
alert(name.attr('placeholder') + " is empty");
return;
}
$.ajax({
url: "your destination",
data: {
name: name.val(),
},
dataType: "json",
type: "POST",
success: function (data) {
if (data['error'] === false) {
alert(data['msg']);
} else {
alert(data['msg']);
}
}
});
}
</script
當然,您只需要 JQ 用於 AJAX 部分,但其余的功能可以僅由 JS 完成。
我建議您嘗試訪問您的 html 並更改其結構,例如“選擇事件”部分可以使用<select>
下拉列表而不是當前的兩個復選框,以便您可以使用更簡潔、更簡潔的required
屬性方法顯示在我發布的另一個答案中。
但是,如果您必須僅使用 JavaScript 來驗證表單,那么您只需檢索表單元素,驗證每個元素並在它們全部通過時提交表單。
為此,您只需用<button>
替換當前的<input type="submit">
元素,然后向該按鈕添加一個單擊偵聽器,該按鈕又將運行一個函數,該函數將阻止使用preventDefault提交表單()方法,檢查並驗證每個表單元素,如果所有元素都通過驗證,則提交表單。
檢查並運行以下代碼片段或打開此JSFiddle以獲得上述方法的實際示例:
const form = document.getElementById("bookingForm"); const events = document.querySelectorAll('input[name="event[]"]'); const terms = document.querySelector('input[name="termsChkbx"]'); const selectBox = document.querySelector('select[name="customerType"]'); const fName = document.querySelector('input[name="forename"]'); const sName = document.querySelector('input[name="surname"]'); const btn = document.getElementById("submitBtn"); function verifyEvents(e){ e.preventDefault(); if(selectBox.value != "" && terms.checked && fName.value != "" && sName != "" && (events[0].checked || events[1].checked)){ console.log(selectBox.value); form.submit(); } else { alert("Please fill the form."); } } btn.addEventListener("click", verifyEvents);
<form id="bookingForm" action="javascript:alert('form submitted');" method="get"> <section id="bookEvents"> <h2>Select Events</h2> <div class="item"> <span class="eventTitle">Thomas Bewick and His Apprentices</span> <span class="eventPrice">0.00</span> <span class="chosen"><input type="checkbox" name="event[]" value="1" data-price="0.00"></span> </div> <div class="item"> <span class="eventTitle">Winter Festival @ Discovery Museum</span> <span class="eventPrice">0.00</span> <span class="chosen"><input type="checkbox" name="event[]" value="12" data-price="0.00"></span> </div> </section> <section id="collection"> <h2>Collection method</h2> <p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p> <p> Home address - £5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked=""> | Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0"> </p> </section> <section id="makeBooking"> <h2>Make booking</h2> Your details Customer Type: <select name="customerType"> <option value="">Customer Type?</option> <option value="ret">Customer</option> <option value="trd">Trade</option> </select> <div id="retCustDetails" class="custDetails"> Forename <input type="text" name="forename"> Surname <input type="text" name="surname"> </div> <div id="tradeCustDetails" class="custDetails" style="visibility:hidden"> Company Name <input type="text" name="companyName"> </div> <p style="color: red; font-weight: bold;" id="termsText">I have read and agree to the terms and conditions <input type="checkbox" name="termsChkbx"></p> <p><button id="submitBtn" name="submitBtn" value="Book now!">Book now!</button></p> </section> </form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.