My script works successfully when I validate a form field using;

<input type="submit" onClick="return chkrange(this.form)"

But, when I remove the onclick from the input type and try to use

onSubmit="return chkrange(this.form)" within the <form> tag it doesn't work

Why not?

Dani AI

Generated

Short diagnosis: the inline click handler on the submit button works because the button’s this is the button, and this.form points to the owning form. When you move the call into the form’s submit handler, this is already the form, so using a .form property there will not work. As pointed out, pass the form itself (or use the event target) rather than trying to read a .form property from the form element. ’s request for the validation code is still a good idea if the problem persists.

Prefer unobtrusive handlers and the submit event so validation runs for any submit action (button click, Enter key, script submit). Example pattern:

const form = document.getElementById('myForm');

form.addEventListener('submit', function (e) {
  if (!validateForm(this)) { // this === the form
    e.preventDefault();      // stop submission when invalid
  }
});

function validateForm(form) {
  const value = form.elements['someField'].value;
  // range checks, set custom messages, return true/false
  return true;
}

Key differences to remember: returning false from an inline onsubmit cancels submission, but returning false from an addEventListener handler does not — you must call event.preventDefault(). Also ensure your script runs after the DOM is ready (or wrap in DOMContentLoaded) and that the submit control is actually type="submit".

Quick troubleshooting checklist: open the console for errors (e.g., undefined property), log this inside the handler to confirm what it is, verify script placement, and add server-side validation as a backup.

Recommended Answers

All 2 Replies

Would have to see the form validation code to say.

Change the onSubmit version to just onSubmit="return chkrange(this)" . Inside the form tag, this already refers to the form.

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.