How to prevent form submission until form is filled using JavaScript?

javascript stop form submit if validation fails
jquery prevent form submit
javascript prevent form submit
how to disable submit button after form submission in javascript
jquery prevent form submit on button click
swap function name temporarily to prevent form submission
javascript submit form
javascript get form values on submit

It should not be possible to submit the form if the user does not enter a value into the text entry fields, e.g. for surname or company, and at least one event has not been selected (remember that users don’t always fill out forms in top to bottom order). Here is the sample code from php file which I can't edit. Only java script must be used.

<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>
Using HTMLFormElement.elements to dynamically set required attribute:

Just use the HTMLFormElement.elements property to get all the form controls (input, select, etc) inside your form and then use the Array.from() method to get a shallow-copied array of the HTMLFormControlsCollection which you can now loop over and use the setAttribute() method to dynamically set a required attribute to all the form controls.

Check and run the following Code Snippet or open this JSFiddle link for a practical example of the above approach:

// 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>

JavaScript code to stop form submission, You can use the return value of the function to prevent the form submission <form name="myForm" onsubmit="return validateMyForm();">. and function like Find Instant Quality Info Now! Get Online Form Submission

1_you can add required attribute to inputs by JS. :)

2_I'm not a pro and the only way I can think of , is using AJAX and JQuery .like this:

<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

you need JQ just for the AJAX part of course, but the rest of the function can get done just by JS.

Preventing Double Form Submission < JavaScript, Using JavaScript to disable form buttons and prevent double submission of A second click on the Submit button before the form has finished� Find Online Form Submission. Check Out 1000+ Results from Across the Web

I would suggest that you try and get access to your html and change it's structure e.g. the "Select Events" section could use a <select> dropdown instead of the current two checkboxes so you can make use of the cleaner and more concise required attribute approach shown in the other answer that I posted.

However, if you HAVE to use only JavaScript to validate the form, then you can just retrieve the form elements, validate each element and submit the form if they all pass.

To do that, you can just replace the current <input type="submit"> element with a <button> instead and then add a click listener to that button which in turn will run a function that will prevent the form from submitting using preventDefault() method, check and validate each form element and submit the form if all the elements pass the validation.


Check and run the following Code Snippet or open this JSFiddle for a practical example of the above approach:

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>

Stop submit until not fill out - JavaScript, How to I prevent/disable submit until not fill out the all textbox. <! that do not support HTML's built-in form validation, you must use JavaScript. It should not be possible to submit the form if the user does not enter a value into the text entry fields, e.g. for surname or company, and at least one event has not been selected (remember that

How to stop form submission using JavaScript?, Use the return value of the function to stop the execution of a form in JavaScript. < form onsubmit = "event.preventDefault(); myValidation();">. How to stop form submission using JavaScript? Use the return value of the function to stop the execution of a form in JavaScript. The JavaScript function would be like the following −. function myValidation () { if (check if your conditions are not satisfying) { alert ("Oops!

Prevent form submit if field empty html, In projects, it is often necessary to prevent form submission after clicking the the HTML form and prevent submitting until all the Required fields are filled out. Step 2) Add JavaScript: If an input field (fname) is empty, this function alerts a� Well, JavaScript has a method that can prevent the default action that belongs to the event. That means the default action will not occur. This is JavaScript preventDefault() event method which can stop the form submission. Now we are going to prevent our form submission that we have just build using the preventDefault() event method of JavaScript. Below is our JavaScript code which can do this job:

HTMLFormElement: submit event, Note: Trying to submit a form that does not pass validation triggers an invalid event. In this case, the validation prevents form submission, and thus� Disable enable form submit button We display a form and then disable the submit button until user enters the data as per requirement and the data validation is completed. Note that we are using all client side JavaScript validation here.

Comments
  • I'm not allowed to edit html, this should be done only with java script.
  • and a small info there are two events in the list, user should choose at least one and choosing every event is not mandatory
  • @Gokul Check the other answer that I have posted.
  • its saying that in line btn.addEventListener("click", verifyEvents); addEventListener is undefined
  • @Gokul Make sure your script tag that has the js is loaded at the end of yout page content otherwise your js will be loaded before the html is even present on the page leading to errors like that one. Move your script to the bottom of your page just above the closing </body> tag.