简体   繁体   中英

return false or e.preventdefault not working

I have one form with one text box and i give 50 char limit in that with below script

Its working fine.

but when i click on submit its will get submit after show a alert message its should not be submitted

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>

please help me to find what is wrong in my script.

If you want to break the submit event, you have to add the handler to the form element, not the button . Otherwise you only handle and break the button, not the form action.

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

Simple live example: https://jsfiddle.net/ukynbn0s/

Try to add click event:

 $("button").click(function(){ // add button click event var value = $("#concept_name").val(); if(value.length > 50){ alert("Maximum limit is 50 character"); return false; // it will not submit form if return false }else{ alert("Form will be submitted"); return true; } }); 
 <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> 

Never use onclick with button declaration because it's like tight coupling coding standards. Instead do it like this:

<button type="submit" id="submitBtn">submit</button>

$("#submitBtn").on('click',function(event){

    var value = $("#concept_name").val();

    if(value.length > 50){
       alert("Maximum limit is 50 character");
       event.preventDefault();
    }

});

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