在使用JavaScript填写表单之前,如何防止表单提交?

时间:2019-12-22 16:04:28

标签: javascript html

如果用户未在文本输入字段中输入值(例如,姓氏或公司,并且至少没有选择一个事件 (请记住,用户并非总是按照从上到下的顺序填写表单)。这是无法编辑的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="">&nbsp; | &nbsp;
            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>

3 个答案:

答案 0 :(得分:0)

使用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="">&nbsp; | &nbsp;
      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 :(得分:0)

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

您当然只需要AJAX部分的JQ,但是其余功能可以完成  只是通过JS。

答案 2 :(得分:0)

我建议您尝试访问HTML并更改其结构,例如“选择事件”部分可以使用<select>下拉列表代替当前的两个复选框,以便您可以使用我在其他发布的答案中显示的更简洁,更简洁的required属性方法。

但是,如果您只需要使用JavaScript来验证表单,则只需检索表单元素,验证每个元素并在表单全部通过后提交表单即可。

为此,您只需将当前的<input type="submit">元素替换为<button>,然后在该按钮上添加一个点击侦听器,该按钮就会运行一个函数,该函数将阻止表单提交使用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="">&nbsp; | &nbsp;
            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>