2

I am working on todos. And, I was looking for submitting Todos through ajax on pressing 'enter' key.

It is working fine. But, there is one problem. It submits data 2 times for every press on 'enter' key. I don't have any submit button. I wanted to have on pressing enter key in textbox (#todos-t_description).

<form id="create-todos-form" action="/misc/todos/index" method="post">

  <input id="todos-t_description" class="t_description form-control" name="Todos[t_description]" type="text">

  <select id="todos-t_case_id" class="form-control" name="Todos[t_case_id]">
      <option value="">Related to case</option>
  </select>

</form>

I Used.

<script>
window.addEventListener("DOMContentLoaded", function() {
  jQuery(document).ready(function($){

    $('.t_description').keydown(function (event){
      if (event.keyCode == 13) {
        $('#create-todos-form').submit();
      }
    });

    $('#create-todos-form').on('submit', function(e) {
      e.preventDefault();
      var form = $(this);
      var formData = form.serialize();
      $.ajax({
        url: "/misc/todos/create",
        type: "POST",
        data: formData,
        success: function (data) {
          $("#todos-t_completed_date").blur(); 
          $('tbody').append(data);
          $('.t_description').val("");
          $('#todos-t_completed_date').val("");
          $('.noTodos').hide();
        },
        error: function () {
          alert("Problem Ocurred");
        }
      });
    });
  });
}, false);
</script>

I don't know what is happening in code. If I put alert before e.preventDefault();. Alert message coming twice too on single 'enter' key press. Even I focus to other textbox after getting success message. But, No. It didn't worked. Any Hint/Suggestions.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Nana Partykar
  • 10,556
  • 10
  • 48
  • 77

3 Answers3

4

The cause

By default, HTML will submit the form when the user press enter on the input. Therefore, in your keydown event, it's submitting once, but since you're not preventing the default, it's submitting another time.

How to fix:

  1. You could remove the keydown event.
  2. If you want to keep it, add a event.preventDefault(); or return false; inside your if case.

For scenario #2, the code would be:

$('.t_description').keydown(function (event){
    if (event.keyCode == 13) {
        $('#create-todos-form').submit();
        event.preventDefault(); // To prevent the default HTML form submission
    }
});

As you can see in this issue here Prevent users from submitting a form by hitting Enter, the form is submitting without any event.

Community
  • 1
  • 1
Chin Leung
  • 14,621
  • 3
  • 34
  • 58
  • Actually, in that page. Edit todos are also there after clicking double on todos. Editable text are coming. Where, I can edit it and submit it again. So, there where I am getting stuck. – Nana Partykar May 06 '16 at 18:48
  • Sorry @NanaPartykar, I did not understand what you meant. Could you try to rephrase that please? – Chin Leung May 06 '16 at 18:56
1

You don't need to bind the keyup or keydown anymore as pressing Enter should submit your form already.

Here's a Fiddle for you.

HTML

<form id="create-todos-form" action="/misc/todos/index" method="post">
  <input id="todos-t_description" class="t_description form-control" name="Todos[t_description]" type="text">
  <select id="todos-t_case_id" class="form-control" name="Todos[t_case_id]">
    <option value="">Related to case</option>
  </select>
</form>

jQuery

$(document).ready(function() {
  $("#create-todos-form").on("submit", function(e) {
    e.preventDefault();
    alert("I was submitted!");
  })
});
dokgu
  • 4,957
  • 3
  • 39
  • 77
  • But, it's not submitting. Because, I have to initialize it on *something*. Right ? So, I initialized it on key press. If i don't initialize it. It never submits. – Nana Partykar May 06 '16 at 18:46
  • @NanaPartykar just remove `$('.t_description').keydown(function (event){ if (event.keyCode == 13) { $('#create-todos-form').submit(); } });` and you should be fine. – dokgu May 06 '16 at 18:48
  • Hi Patrick, I already tried this. But, no. It's not working. I tried now itself. But, no. Same result. I tried it through different ways. But, when I got same result from every case. I thought to ask in SO. Your answer is very correct. I know that. But, why in my case, it's not working. – Nana Partykar May 06 '16 at 18:50
  • @NanaPartykar Why is your `action` from the `form` and `url` from `AJAX` not the same? Shouldn't you be submitting to only one page? – dokgu May 06 '16 at 18:54
  • @NanaPartykar check my answer again, I added a fiddle for you to look at and test. – dokgu May 06 '16 at 18:59
  • This is the correct answer. When the enter key is pressed while the form has focus it will trigger the form submit. I bet the event is bubbling up so it looks like it's triggering twice. – wirey00 May 06 '16 at 19:04
0

Try not binding the keydown event to the input field. Pressing enter in the input field appears to be triggering the submit action on the form automatically. Binding it yourself is where the duplicate comes from.

timehat
  • 135
  • 6
  • But, for textbox I have to use any function like `keydown` or `keypress`. Without this. How it can be possible. – Nana Partykar May 06 '16 at 18:39
  • @NanaPartykar It's input. And it's inside the form. The `submit()` function knows if an enter is a submit, I guess. – Chay22 May 06 '16 at 18:41
  • Yes, the browser captures the enter keypress within the text field and triggers the submit event automatically. You don't need to do this manually. :) – timehat May 06 '16 at 18:43