Jason Jason - 6 months ago 26
jQuery Question

Prevent button jquery

I am using jQuery for min and maxlength. I want here to prevent button if minlength is not correct. I mean if user not entered minimum 8 digit, then prevent button.

jQuery:

var minLength = '8';
var maxLength = '13';
$("input[name=354]").keypress(function(){
if(this.value.length > maxLength) {
this.value = this.value.slice(0, maxLength);
}
if(this.value.length < minLength) {
$(this).css('border','1px solid #f00');
} else {
$(this).css('border-color','#cfdadd');
}
});


HTML button code:

<button type="button" class="btn next">Next</button>

Answer

You can add disabled attribute to button if length of input isn't valid.

var minLength = "5";
var maxLength = "10";
$("input").on("keydown change", function(){
    var value = $(this).val();
    
    // length is short
    if (minLength > value.length){
        $("button").attr("disabled", true);
        $(this).addClass("error");  
    } else {
        $("button").attr("disabled", false);
        $(this).removeClass("error");  
    }
    
    // length is long
    if (value.length > maxLength)
        this.value = value.slice(0, maxLength);    
});
.error {
    border: 2px solid rgba(255, 0, 0, 0.48);
    box-shadow: 0px 0px 2px -1px red;  
    outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <input type="number" class="error" />
    <button type="submit" disabled>Submit</button>
</form>

Comments