P_M P_M - 5 months ago 12
jQuery Question

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.

Answer

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();
    }

});
Comments