Skip to content

Instantly share code, notes, and snippets.

@xav76
Created October 24, 2012 16:30
Show Gist options
  • Save xav76/3947153 to your computer and use it in GitHub Desktop.
Save xav76/3947153 to your computer and use it in GitHub Desktop.
A CodePen by T.J. Fogarty. Comment with character counter - Simple character counter with a custom min and max comment length. Not much in the way of validation, just something simple.
<form id="enquiry" action="">
<textarea maxlength="140" name="message" id="message" placeholder="Add your comment!"></textarea>
<input type="submit" value="Add Comment">
</form>
$(document).ready(function () {
var comment = $('form#enquiry textarea'),
counter = '',
counterValue = 140, //change this to set the max character count
minCommentLength = 10, //set minimum comment length
$commentValue = comment.val(),
$commentLength = $commentValue.length,
submitButton = $('form#enquiry input[type=submit]').hide();
$('form').prepend('<span class="counter"></span>').append('<p class="info">Min length: <span></span></p>');
counter = $('span.counter');
counter.html(counterValue); //display your set max length
comment.attr('maxlength', counterValue); //apply max length to textarea
$('form').find('p.info > span').html(minCommentLength);
// everytime a key is pressed inside the textarea, update counter
comment.keyup(function () {
var $this = $(this);
$commentLength = $this.val().length; //get number of characters
counter.html(counterValue - $commentLength); //update counter
if ($commentLength > minCommentLength - 1) {
submitButton.fadeIn(200);
} else {
submitButton.fadeOut(200);
}
});
});
body {
background: #444;
font-family: 'Open Sans', sans-serif;
}
form {
position: relative;
top: 40px;
border-radius: 4px;
width: 400px;
height: 180px;
margin: 0 auto;
}
form textarea {
border-radius: 2px;
box-shadow: 0px 2px 11px 0px rgba(0, 0, 0, 0.3);
border: 1px solid #e2e6e6;
margin: 10px 0 10px 0;
font-family: 'Open Sans', sans-serif;
outline: none;
width: 395px;
height: 100px;
}
form span.counter {
float: right;
color: #f2f2f2;
}
form p.info {
font-size: 11px;
color: #999;
}
form p.info > span {
color: #fff;
}
form input[type=submit] {
cursor: pointer;
box-shadow: 0px 2px 11px 0px rgba(0, 0, 0, 0.3);
border: 1px solid #A8F1FF;
border-radius: 2px;
background-color:#0093B0;
color: #fff;
float: right;
padding: 10px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment