简体   繁体   中英

JQuery form submit with function not working

I'm having an issue with the jquery function submit for a form :

$(document).ready(function () {
    $('#message').keydown(function(e) {
      if(e.which == 13 && !e.shiftKey) {
         $('#edit_message_11').submit(function() {
            alert("HELLO2");            
         });            
         return false;
      }
    }); 
}); 


<form id="edit_message_11" class="edit_message" method="post" action="/message/11" accept-charset="UTF-8">
<textarea id="message" class="form-control edit_message_form" name="message">
Hello
</textarea>

http://jsfiddle.net/978QC/

When I do the following for my form : $('#edit_message_11').submit(function() { ... }); it doesn't trigger the submit.

However, If I do $('#edit_message_11').submit(); it does trigger the submit.

The reason why I need to do $('#edit_message_11').submit(function() { ... }); is because I want to do an ajax submit.

Anyone has a clue?

Thanks!

I don't believe it will work the way you are trying to do it. When it's inside the submit function, the alert will never fire until it gets a response back from POST. Which means you need a response from your form processing script.

Your AJAX call doesn't need to be inside the submit function, it just needs to be inside the event.

$(document).ready(function () {
    $('#selfie_message').keydown(function(e) {
      if(e.which == 13 && !e.shiftKey) {
         $('#edit_selfie_11').submit();           

         $.ajax({
         type: "POST",
         url: "/selfies/11",
         data: $("#edit_selfie_11").serialize()
         });
       }
    }); 
});

If you need something to happen on success, you would do it like this.

$(document).ready(function () {
    $('#selfie_message').keydown(function(e) {
      if(e.which == 13 && !e.shiftKey) {
         $('#edit_selfie_11').submit();           

         $.ajax({
         type: "POST",
         url: "/selfies/11",
         data: $("#edit_selfie_11").serialize(),
         success: function(response){
         //your response code here//
         }
         });
       }
    }); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM