3

I had a form as below:

    <form name="attachment_form" id="id_attachment_form" class='class_attachment_form' action="/visit/something/" method="post" enctype="multipart/form-data">
        <table class="datagrid item_list" id="id_attachments">
            <tbody>
                    <td>
                        *Accession Number: <input id='acc_number' type="text" name="accession_number">
                    </td>                
            </tbody> 
            <input type="submit" value="Submit"/>

    </form>

<script>
$(document).ready(function () {
    $( "#id_attachment_form" ).submit(function( event ) {
        var accession_number = $('#acc_number').val();
        if (!accession_number)
            {
              alert("Please provide Accession Number");
              console.log('redirecting===>1');
              event.preventDefault();
              console.log('redirecting===>2');
            }
        else
            {    
                var url = '/visit/' + accession_number
                $(".class_attachment_form").attr("action", url);
                
            }
    });

});
    
</script>

So when I tried this on Firefox and submitted the form without value for Accession Number it was displaying the pop-up with some message, but it was also redirecting to url in the form action attribute event.preventDefault(); is not working, its not stopping the form redirection.

Similarly when I tried the same procedure on Google, the weird thing is even the pop-up was not displaying.

So why the event.preventDefault(); was not working, and why the pop up is working on Firefox and not working on Chrome?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Shiva Krishna Bavandla
  • 25,548
  • 75
  • 193
  • 313

2 Answers2

1

Instead of using "event.preventDefault()" you should just use "return false".

Cheers

0

Because you are trying to preventdefault on while Submitting the form, not in onClick. So better use return false behalf of event.preventDefault(). Though its working on other browser thats not correct way.

kirubakar
  • 191
  • 1
  • 6
  • 1
    Who says its not the correct way? Source please. MDN seems to thinks it is the correct way: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event – B T Jun 20 '19 at 21:53