Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add character count for inputs and textareas #2162

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
reformatted code and added validation system
biskwikman committed Aug 11, 2022
commit 0275404fe756d9b53c65ce77af6245e29e2305e4
55 changes: 35 additions & 20 deletions js/10-base.js
Original file line number Diff line number Diff line change
@@ -121,28 +121,43 @@ Liberapay.init = function() {
location.reload();
});

// Create dynamic hint based on remaining length
$('input[maxlength], textarea[maxlength]').on('focus input', function() {
if (!maxLength) {
var maxLength = $(this).attr('maxlength');
$(this).data('maxLength', maxLength);
$(this).removeAttr('maxLength');
}

var maxLength = $(this).data('maxLength');
var remainingLength = maxLength - $(this).val().length;
var helpBlock = $(this).siblings('.help-block');
// Selector for inputs and text areas with max lengths
var $maxLengthTextAreas = $('input[maxlength], textarea[maxlength]');

// Add remaining length indicator on page load
$maxLengthTextAreas.each(function() {
var $this = $(this)
var maxLength = $this.attr('maxlength');
$this.data('maxLength', maxLength);
$this.removeAttr('maxLength');

maxLength = $this.data('maxLength');
var remainingLength = maxLength - $this.val().length;
$this.after("<span class='remaining-length'>" + remainingLength + "</span>");
});

if ($(this).val().length) {
helpBlock.text(function (index, value) {
return value.slice(value.indexOf('.') + 1);
});
helpBlock.prepend(remainingLength + ' characters remaing.');
// Style remaining length indicator
$('.remaining-length').each(function() {
$(this).css({
'float': 'right',
'margin-right': '5px'
});
})

// Update remaining length dynamically
$maxLengthTextAreas.on('focus input', function() {
var $this = $(this)
var maxLength = $this.data('maxLength');
var remainingLength = maxLength - $this.val().length;
$this.siblings("span[class='remaining-length']").first().text(remainingLength);

var constraintPattern = '^[\\s\\S]{1,'+ maxLength +'}$';
var constraint = new RegExp(constraintPattern, '');

if (constraint.test($this.val())) {
$this.get(0).setCustomValidity('');
} else {
helpBlock.text(function (index, value) {
return value.slice(value.indexOf('.') + 1);
});
helpBlock.prepend('Maximum length is ' + maxLength + '.');
$this.get(0).setCustomValidity('too many characters');
}
});
};