-2

I want Enter Key not to submit a form. I did this first.

  $("#send_c").keypress(function(e) {
    if (e.which == 13) {
      e.preventDefault();
      return false;
    }
  });

But the button and Enter key work the same. Nothing happens or submitted even by the Enter key. My second try is this.

<%=form_for [@article, @article.comments.build], remote: true, :onsubmit=>"return false;" do |f| %>
  <%=f.text_field :body, id: "c_i"%>
  <%=f.button :submit, id: "send_c"%>
<%end%>

This did not work. The form is submitted both by Enter key and submit button.

What could be wrong?

Brad Werth
  • 17,411
  • 10
  • 63
  • 88
Arch
  • 133
  • 5

2 Answers2

3

The problem with your code is the selector

$("#send_c").keypress(function(e) {
      if (e.which == 13) {
        e.preventDefault();
        return false;
      }
    });

$("#send_c") is a selector of submit button, instead you may have to give the selector as $(window) You can use the below script to accomplish the task

$(document).ready(function() {
  $(window).keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
});

For reference please see this issue

Community
  • 1
  • 1
0

In javascript:

function x13(x) { if(x.keyCode==13) return false; }

In html:

<input onkeypress="return x13(event)">
iAmOren
  • 2,760
  • 2
  • 11
  • 23