preventDefault runs only once

Greetings, this trigger works correctly ONE time. If it fires again, it just refreshes my page, so I’m guessing that the preventDefault isn’t working. Am I missing something?

function watchForm() {
$(‘form’).submit(event => { //listening for event on the pop-up menu
event.preventDefault(); //suppresses browser from going to a linked page (that isnt reall linked) so this page can be updated.
let searchState = $(’#js-stateMenuForm :selected’).val(); //invoked state code value stored in searchState
getParks(searchState); //calls getParks and sends the state code

Hello and Welcome!

Which browser are You using? Have You tried different ones? Are there any errors displayed on the browser console?

Try putting your event.preventDefault(); at the end of your function?
Let us know if you find out what the issue was or if you are still stuck :slight_smile:

I’m testing locally on my own iMac. Results are consistent on Chrome, Firefox, Safari, Opera, and Firefox developer edition. No errors.

Tried your suggestion.
Still reRendering.

Hmm, try using event.preventDefault(); AND event.stopPropogation();?
OR have you tried returning false at the end of the function instead of the e.preventdefault?

This SO might help with regards to why, (if it fixes).

I’ve tried both of those. stopPropagation still reloads page.
retrun false stops the submit button from doing anything.

1 Like

Just to make sure, before I am all out of ideas, you used preventDefault and then stopPropagation together?

Sorry, hopefully someone else knows this magic.

Yep, Both together, AND separately.

Unfortunately I’m still a FCC noob, so I can’t link to my code at yet.

If you open some topics and do the guide at the start you unlock the basic member level :slight_smile:

Have you tried using to post your code?

If so, just post your codepen profile name and the name of the pen.

I use but can use codepen. The problem is that I cant post the link to until I get some badges here. Not sure how long that will take.

Without seeing how your are calling your watchForm, it is difficult to help. Seeing the full code would make it clearer.

I suppose you could also post your profile name and session name and we could find it that way also.

I found your project.


@gadgetwerx You have two problems.

  1. You need to call watchForm again inside your displayResults function right after you call stateMenu('nav');

  2. You need to empty the div with id=“parks” after the same call to watchForm inside your displayResults function. Otherwise, the results keep getting appended to the end of the section instead of being at the top.

That didn’t work. On choosing a state, and hitting Go, the div just emptied and left an empty field.

I modified your original repl session and seems to work for me unless I have misunderstood something.

1 Like