return false或e.preventdefault not working

时间:2016-06-24 06:10:37

标签: javascript jquery ruby-on-rails

我有一个带有一个文本框的表单,我用下面的脚本

给出50个字符限制

工作正常。

但是当我点击提交时,它会在显示提醒消息后获得提交 它不应该提交

function charLimit(e) {
    var value = $("#concept_name").val();
    if(value.length > 50){
      alert("Maximum limit is 50 character");
      return false;
    }else{
      return true;
     } 
<%= f.text_area :name, rows:1 , :required => true, :onkeypress=> "charLimit()" %>

<button type="submit" onclick="charLimit()">submit</button>

请帮我查一下我的剧本中的错误。

3 个答案:

答案 0 :(得分:1)

如果要中断submit事件,则必须将处理程序添加到form元素,而不是button。否则你只处理和破坏按钮,而不是表单动作。

<form action="foo.html" onsubmit="return charLimit()">
    <!-- content -->
    <button type="submit">submit</button>
</form>

简单实例:https://jsfiddle.net/ukynbn0s/

答案 1 :(得分:1)

尝试添加点击事件:

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<form method="post">
  <textarea id="concept_name" name="concept_name"></textarea>
  <button type="submit">submit</button>
</form>
&#13;
{{1}}
&#13;
&#13;
&#13;

答案 2 :(得分:1)

永远不要使用带按钮声明的onclick,因为它就像紧耦合编码标准。而是这样做:

df1 <- structure(list(Person = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L), Event = c("A", "A", "B", "B", "B", "B", 
"B", "A", "B", "A", "B", "A", "A", "A", "A"), EventDate = c("22/03/15", 
"22/05/15", "12/12/15", "12/12/15", "01/13/12", "02/03/12", "03/08/14", 
"05/09/14", "02/02/02", "03/05/14", "03/06/14", "17/11/15", "17/02/16", 
"18/05/16", "23/06/16")), .Names = c("Person", "Event", "EventDate"
), class = "data.frame", row.names = c(NA, -15L))