0

I am using wtforms and here is my submit button:

{{ form.submit(class="btn btn-outline-info") }}

And This is my onbeforeunload function:

<script type="text/javascript">
  window.onbeforeunload = function() {
  return "Are you sure you want to navigate away?";
  }
</script>

I know in normal html forms I can probably use jquery to do this:

reference:

jquery-function-before-form-submission stackoverflow discussion

clear onbeforunload stackoverflow discussion

<head>
  <script src="jquery-3.5.1.min.js"></script>
</head>
<script>
$('#myform').submit(function(event) {

 event.preventDefault(); //this will prevent the default submit

  window.onbeforeunload = null;
  
 $(this).unbind('submit').submit(); // continue the submit unbind preventDefault
})
<script>

What should I do when I am working with these wtforms object? (p.s. I am not familiar with js or jquery....please point out what I done wrong if any....)

Thanks in advance!

1
  • 1
    I doubt you need to call preventDefault(). if you plan to submit any way. I'd just set onbeforeunload to null and return true (returning true lets the submit continue). Commented Jan 13, 2021 at 20:51

2 Answers 2

1

An option is to use addEventListener instead of onbeforeunload

const myFunc = function() {
  return "Are you sure you want to navigate away?";
}
window.addEventListener('beforeunload', myFunc);

and then on the submit method, remove the listener

window.removeEventListener('beforeunload', myFunc);
Sign up to request clarification or add additional context in comments.

Comments

0

So this is probably not the best way to do it! But it's a really good work-around! since wtforms object does not allowed passing any additional function i.e. onclick or whatsoever information into the {} curly bracket a work-around is to wrapped it! so the main thing about adding all those thing is to call a function to disable the onbeforeunload and thus a quick solution will be

onbeforeunload function(stay the same):

<script type="text/javascript">
  window.onbeforeunload = function() {
  return "Are you sure you want to navigate away?";
  }
</script>

disable onbeforeunload function:

<script>
  function submit()
  {
    window.onbeforeunload = null;
  }
</script>

and for submit button:

<a onclick="submit()">{{ form.submit(class="btn btn-outline-info") }}</a>

Couldn't imagine this took me so long to figured it out, btw thanks @terrymorse who made me figured out how easy the question actually is! Thanks to all who comments and provide solution and edit my questions!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.