Hi

I have a form on which I run some validation, if any of the conditions fail I show an alert. For example for the name field

<input type="text" name="name" id="name">
if(trim(cname.value) == '')
   {
      alert('Enter a Name');
      cname.focus();
      return false;
   }

This is called when a user clicks the make booking button:

<input type="button" onclick="return checkForm(); MakeBooking();" value="Book" />

This alert work fine when a user does not enter a name, however when the form entries are valid the MakeBooking() is not getting called.

Do I need to change something so this is called after the validation?

Dani AI

Generated

resolved the immediate problem after and called out the flow issue. For a more robust, maintainable approach, avoid chaining inline return/onclick expressions and instead attach a single submit handler that runs validation and only proceeds when validation succeeds.

A safe pattern is to let the form handle submit (so Enter works) and use an event listener to prevent default submission for AJAX workflows:

<form id="bookingForm">
  <!-- form fields -->
  <button type="submit">Book</button>
</form>

<script>
document.getElementById('bookingForm').addEventListener('submit', function (e) {
  e.preventDefault();
  if (checkForm()) {
    MakeBooking();
  }
});
</script>

Use addEventListener and preventDefault to control flow rather than inline onclick (MDN: addEventListener, preventDefault).

Common troubleshooting checklist if MakeBooking still seems not to run:

  • Check the browser console for uncaught errors; any exception will stop later code.
  • Ensure checkForm() always returns a boolean (explicitly true on success).
  • Avoid naming collisions: form controls with name or id equal to a function can shadow globals (see named access on window: WHATWG spec).
  • If validation is asynchronous (AJAX/server checks), have checkForm return a Promise and call MakeBooking() in the .then() callback.

Following the submit-handler pattern makes the logic clearer, fixes Enter-key behaviour, and reduces subtle bugs like the one discussed in this thread.

Recommended Answers

All 3 Replies

you are returning, so when will it ever get to MakeBooking?

I agree to sillyboy as you wrote return statement so program control will be immediately returned to the checkform() again.

Hi thanks, I didnt realise that is what the control part meant, I have removed that now.
Cheers

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.