I have my solution working 90% and the Submit button disables when the user enters more valid characters, but as soon as the user clicks on the next input, the button turns on again.
Below I tried to add an if statement, but it doesn't seem to make any difference. Help would be greatly appreciated. also there is a lot of code that is repeated for the three inputs to limit the characters as their number is different, id is there a better way to write this?
function characterLimit() {
var headingMax = 20;
var ribbonMax = 15;
var descriptionMax = 120;
var dh = $('.heading-max');
var dr = $('.ribbon-max');
var dd = $('.description-max');
var btnSubmit = $('#submitBtn');
var inputTitle = $('#createDealTitle');
var inputRibbon = $('#createDealRibbon');
var inputDescription = $('#createDealDescription');
dh.html(headingMax);
dr.html(ribbonMax);
dd.html(descriptionMax);
inputTitle.keydown(function(){
var textLength = $(this).val().length;
var textRemaining = headingMax - textLength;
dh.html(textRemaining);
if (textLength > headingMax) {
dh.addClass('error-text');
$(this).addClass('error-input');
btnSubmit.attr('disabled', true).addClass('disabled');
}else {
dh.removeClass('error-text');
$(this).removeClass('error-input');
btnSubmit.attr('disabled', false).removeClass('disabled');
}
});
inputRibbon.keydown(function(){
var textLength = $(this).val().length;
var textRemaining = ribbonMax - textLength;
dr.html(textRemaining);
if ($(this).val().length > ribbonMax) {
dr.addClass('error-text');
$(this).addClass('error-input');
btnSubmit.attr('disabled', true).addClass('disabled');
}else {
dr.removeClass('error-text');
$(this).removeClass('error-input');
btnSubmit.attr('disabled', false).removeClass('disabled');
}
});
inputDescription.keydown(function(){
var textLength = $(this).val().length;
var textRemaining = descriptionMax - textLength;
dd.html(textRemaining);
if ($(this).val().length > descriptionMax) {
dd.addClass('error-text');
$(this).addClass('error-input');
btnSubmit.attr('disabled', true).addClass('disabled');
}else {
dd.removeClass('error-text');
$(this).removeClass('error-input');
btnSubmit.attr('disabled', false).removeClass('disabled');
}
});
if (inputTitle.val().length > headingMax || inputRibbon.val().length > ribbonMax || inputDescription.val().length > descriptionMax) {
btnSubmit.attr('disabled', true).addClass('disabled');
}else {
btnSubmit.attr('disabled', false).removeClass('disabled');
}
}
characterLimit();
https://jsfiddle.net/gavinthebarbarian/5n9d1Lq2/
source
share