Form submitted twice in Chrome/Safari

I am seeking to perform a basic form post, but the following submits to the server twice in Chrome and Safari (but behaves as expected in Firefox):

<form id="create-deck-form" action="/decks/create" method="post">
  <fieldset>
    <legend>Create new deck</legend>
    <label for="deck-name-field">Name</label>
    <input id="deck-name-field" name="deck-name-field" type="text" value="" maxlength="140" />

    <label for="tag-field">Tags</label>
    <input id="tag-field" name="tag-field" type="text" value="" maxlength="140" />

    <input class="add-button" type="submit" value="Create" />
  </fieldset>
</form>

I would like to use the onsubmit attribute to perform validation on the fields before submission, but wherever the return value is true , the form is submitted twice.

I have sought to bind a jQuery handler to the form, but here too, where the default behaviour is not prevented, the form is submitted twice, eg:

<script type="text/javascript">
 $(document).ready(function() {
     $("#create-deck-form").submit(function(event){
          if($("#deck-name-field").val() == "") {
            event.preventDefault();
            alert("deck name required");
          }
        });
 });
</script>

While I suppose there is something blindingly obvious wrong here to a fresh pair of eyes, I am deeply confused why submission, with or without validation, makes a duplicate post to the server in Chrome and Safari. I'd be grateful for any insight.


This issue is actually associated with Facebox (http://defunkt.github.com/facebox/). Facebox initialization causes a second set of requests after your page loads. So, if you post to /myaction/create , Facebox will start a second set of requests with the base URL set to /myaction/create . A fix is to redirect to a URL which handles get requests after doing a post, so you don't end up performing the post twice. Thanks very much for your help.


I'm not 100% sure, but please try this one:

<script type="text/javascript">
   $(document).ready(function() {
      $("#create-deck-form").submit(function(event){
         if(!$("#deck-name-field").val().length) {
           return false;
         }
       });
   });
</script>

if that does not work, please have a look at

for(e in $("#create-deck-form").data('events'))
    alert(e);

This will alert you all events which are bound to your form . Maybe there are more event handlers? Otherwise also alert/log

$("#create-deck-form").attr('onclick')

and

$("#create-deck-form").attr('onsubmit')

just in case.


Can you try return false; after your alert and remove event.preventDefault(); . Maybe you also need return true; in your else-clause. I believe I have that working somewhere.

链接地址: http://www.djcxy.com/p/46706.html

上一篇: 查看输出中的ASP.NET MVC2 CrAzY字符

下一篇: 表单在Chrome / Safari中提交两次