hello.
i have a page where if you don't select an option an alert message is displayed(i'm using javascript and php). when the user clicks 'ok' the parent page is refreshed. i don't want this(the refreshing). can anyone tell me what to do?

Dani AI

Generated

Short summary: the page was reloading because the form submission continued after the validation alert. solved it by stopping the submit, and pointed out returning the validation result from the validator is the cleaner approach. Below are safer, modern alternatives and quick troubleshooting notes to avoid the refresh without relying on blocking alerts.

Prevent submission with the DOM event (preferred)

var form = document.getElementById('myForm');
form.addEventListener('submit', function (e) {
  if (!validateForm()) {
    e.preventDefault();   // stops the navigation
    // show a message or highlight fields instead of alert()
  }
});

Avoid implicit submit buttons / use JS submit

<button type="button" id="saveBtn">Save</button>

document.getElementById('saveBtn').addEventListener('click', function () {
  if (validateForm()) {
    fetch('/submit', { method: 'POST', body: new FormData(form) })
      .then(/* handle response without full page reload */);
  }
});

Use built-in validation where possible

  • HTML5 required, pattern, form.checkValidity() and form.reportValidity() give native validation UI and prevent submit when invalid.

Troubleshooting checklist

  • Confirm your submit handler runs (put a console.log at the top).
  • If the page still reloads, search for other code calling form.submit() or an anchor with href="#" that triggers navigation.
  • Prefer inline messages or DOM highlights over alert() for better UX and fewer surprises.
  • If you keep inline handlers, ensure the handler returns the appropriate value back to the submit event (otherwise the browser will continue the submit).

These approaches prevent the form navigation robustly and are easier to maintain than relying on modal alerts.

Recommended Answers

All 3 Replies

i got it...just had to add a return false to my onsubmit.

onsubmit="check();return false;"

i also added a return false after the alert() statement..

If you have the check() function return false, you can remove the return false; from your onsubmit event.

It's just a bit cleaner that way ;-)

ok...thank you :)

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.