Stec Records Forum

Tools to make music

News: We are back.  We've updated the look of the forum with a new "theme" that works better on mobile devices. Also note that we check all new user requests for spam violations. If you believe you have been rejected unfairly please contact us and we will attempt to resolve it with you.  - Stecrew

Dynamically created Javascript form triggers a page reload (Read 1421 times)

  • Administrator
  • Hero Member
  • Chief Administrator
  • Posts: 771
  • Karma: +0/-0
  • Time reveals truth.
    • Bob Sellon's Home Page
Problem:
I dynamically created a search form using Javascript  with an onclick handler for a "Begin Search" button assigned to a function that performed the search.  I'd used  a div for the form in the past but if you use an actual form entity, the browser will provide the user with previous values. This is really helpful on log-in forms.  I'm trying to eliminate or minimize page reloads so the search happens in the background. The search actually uses the same query mechanism used to load the default page content but was crashing the page (or so I thought) when run from my search form; it got part way through the http request when the page would suddenly reload.

Solution:
It seems so obvious now but it took me an embarrassing amount of time to figure out, which is why I'm posting this to the forum (for others and my future-self).

It turns out that the page was not, in fact, crashing but instead performing the standard load all forms do if you click a button in them.  I thought that I was trapping the onclick event with my function but forgot that the event gets forwarded along to the browser triggering the page reload.  I was so sure it was crashing that I was ignoring expected behavior.

The fix was easy (of course) though not obvious if you're at all new to Javascript events: add "return false" to the end of the onclick function. This tells the browser to discard the event instead of processing it (i.e. using it to Submit the form).