Textarea Character Limit, and Whitespace Trim - javascript

I am having trouble creating a code in javascript to limit characters in an input box and trim whitespace. I am asked to use document.getElementById(, onkeyup event handler, and String.split().
I could only do this:
<script>
TextareaElement(document.getElementById("myWordsToCount"));
myTextareaElement.onkeyup = function(){
var maxlimit = 20;
var counter = maxlimit - information.value.split(/^\s+|\s+$/gm,'').length;
}
</script>
I am so new to javascript and I am thinking it might not be my zone. Anyways, I would deeply appreciate any help I could get.
Thanks

For limiting length you should use maxlenght like
input type="text" maxlength="20"
And for trim
var a =document.getElemenyById("YourId").value;
var str=a.trim();

This could be done with Jquery instead of typical JavaScript.
You could do it like :
//Now Assuming your text area has an id of "#text"
var text = document.getElementById('#text').val();
var trim = $.trim(text);
var characters = 100; //you could change the number of characters you want
$("#counter").append("You have <strong>"+ characters+"</strong> characters remaining");
$("#text").keyup(function(){
if($(this).val().length > characters){
$(this).val($(this).val().substr(0, characters));
}
var remaining = characters - $(this).val().length;
$("#counter").html("You have <strong>"+ remaining+"</strong> characters remaining");
if(remaining <= 10)
{
$("#counter").css("color","red");
}
else
{
$("#counter").css("color","black");
}
You could also turn the above code into a function so that you could call this every time the user enter some text in the textbox.

Related

Limit number of characters in input fields without editing HTML

I'm building a database of people on a WordPress website using this plugin.
I want to limit the number of characters the user can enter in certain fields (textarea and input type="text") in the signup form. Since I'm using a plugin, I can't edit the HTML of the page, so I can't just use the maxlength attribute.
How can I limit the number of characters the user can enter - and preferably also show a remaining characters count - without access to HTML? Can you tell me which files to edit, what code to use and where to put it?
You could use jQuery to set the max length as well as append: a remaining character count
$("input").each(function() {
var $this = $(this);
var maxLength = 50;
$this.attr('maxlength', maxLength);
var el = $("<span class=\"character-count\">" + maxLength + "</span>");
el.insertAfter($this);
$this.bind('keyup', function() {
var cc = $this.val().length;
el.text(maxLength - cc);
});
});
http://jsfiddle.net/0vk3c245/
You would just need to specify which input you want to apply the function to by altering "input" on the first line as well as changing the maxLength variable based on your max characters allowed for each. You could modify this function to take in parameters for multiple fields as well.
Here is a modified version that lets you apply this to multiple inputs:
http://jsfiddle.net/0vk3c245/1/
This is really easy to do with MagJS.
Here is a full working example:
HTML :
<div id="limit">
<h2>Characters left: <length/></h2>
<input>
<textarea></textarea>
</div>
JS:
var demo = {}
demo.view = function(state, props) {
state.textarea = state.input = {
_oninput: function() {
state.length = props.limit - this.value.length;
if (this.value.length > props.limit) {
alert('max length reached:' + props.limit)
this.value = this.value.substr(0, props.limit)
}
}
}
}
var props = {
limit: 10,
}
mag.module("limit", demo, props)
Here is link to working example: http://jsbin.com/sabefizuxi/edit?html,js,output
Hope that helps!

How Do I Add Ellipses to Text

I am trying to create a function that will take an element's text, cut off any characters beyond 80, and add an ellipses if necessary. Here's my code so far:
var maxLength = 80;
function shorten(element) {
var text = $('#' + element).text();
var ret = text;
if (text.length > maxLength) {
text = text.substr(0,maxLength-3) + "...";
}
$('#' + element).text(text);
}
shorten('slide1');
So, the function should take the element, remove extra text off the end, add an ellipses, and then replace the old text in the element with the new string I've just created.
When I run the function, I don't get any errors, but it doesn't actually cut off the text as it should. Why is this?
var text = "Some Text Goes Here. La La La La!";
var textLength = 10; // Number of characters to cut off after
function shorten(text, textLength){
if(text.length > textLength){
text = text.substring(0, textLength) + '…';
}
return text;
}
var shortText = shorten(text, textLength);
Also, using the HTML character for ellipsis is better than using three periods.
I've added a Codepen showing the code working. Additionally, I added a function spaceShorten that will split your text at the last occurrence of a space that is less than the length provided, so you don't split the text mid word.
http://codepen.io/supah_frank/pen/EaYzNz

Error in counting total characters in Jquery

I have a textarea. I restrict users to enter only 100 characters in that textarea using jQuery. It works fine..But my code counts space also. I don't want my function to count space as a character. All other inputs from keyboard be counted as a character excluding space.
Here's my jQuery function.
$(document).ready(function(){
var totalChars = 100; //Total characters allowed in textarea
var countTextBox = $('#counttextarea') // Textarea input box
var charsCountEl = $('#countchars'); // Remaining chars count will be displayed here
charsCountEl.text(totalChars); //initial value of countchars element
countTextBox.keyup(function() { //user releases a key on the keyboard
var thisChars = this.value.replace(/{.*}/g, '').length; //get chars count in textarea
if(thisChars > totalChars) //if we have more chars than it should be
{
var CharsToDel = (thisChars-totalChars); // total extra chars to delete
this.value = this.value.substring(0,this.value.length-CharsToDel); //remove excess chars from textarea
}else{
charsCountEl.text( totalChars - thisChars ); //count remaining chars
}
});
});
my HTML Code is given below:
<textarea name="counttextarea" id="counttextarea" cols="30" rows="8"></textarea><br />
<span name="countchars" id="countchars"></span> Characters Left
Here's a fiddle http://jsfiddle.net/6C8zn/
Your regular expression is not correct.
Instead of
var thisChars = this.value.replace(/{.*}/g, '').length; //get chars count in textarea
Use either of these
var thisChars = this.value.replace(/ /g, '').length;
var thisChars = this.value.replace(/\s/g, '').length;
DEMO

How to count and limit the text from 2 text fields in a form?

i tried to count and limit the user inputs from two text fields. that means max char is 20, then user can enter only 20 char in both text fields.I tried like this
$(document).ready( function() {
jQuery.fn.getLength = function(){
var count = 0;
var max=$("#max").val();
this.each(function(){
count += jQuery(this).val().length;
});
var rem=max-count;
return rem;
};
var $inputs= jQuery('#left,#right');
$inputs.bind('keyup',function(){
var remain=$inputs.getLength();
jQuery('#count').html($inputs.getLength());
$("#left").keyup(function(){
if($("#left").val().length > remain){
$("#left").val($("#left").val().substr(0, remain));
}
});
$("#right").keyup(function(){
if($("#right").val().length > remain){
$("#right").val($("#right").val().substr(0, remain));
}
});
});
});
but it only works for single text box, doesn't take values from 2 fields. any help please..
All you need is this code, it detects the keypress in either #left or #right, if the count of the two is more than 20, it removes the last character typed
$("#left,#right").keyup(function () {
var charCount = $('#left').val().length + $('#right').val().length;
if (charCount > 20) {
difference = -Math.abs(charCount - 20);
$(this).val($(this).val().slice(0, difference));
}
});
Demo http://jsfiddle.net/k8nMY/
My first solution worked on keydown and used return false to stop further entry, however this had the effect of disabling backspace and other keys.
This solution, which executes on keyup waits until after the key is pressed then counts characters. If the number is over 20 it will remove the last character typed. This way, the user can still press backspace and make changes as they wish, but not go over 20 chars.
I have also modified the script further, what it does is detect ANY change, e.g. a paste of a long string. It removes the 'difference' above 20 characters.
This should be a complete solution to the problem.
DEMO: http://jsfiddle.net/EEbuJ/2/
JQuery
$('#left, #right').keyup(function(e) {
if (maxLen() <= 20)
{
// Save the value in a custom data attribute
$(this).data('val', $(this).val());
} else {
// over-ride value with saved data
$(this).val($(this).data('val'));
}
});
function maxLen() {
var x = 0;
$('#left, #right').each(function() {
x += $(this).val().length;
});
return x;
};
This will save the typed in value for your inputs to a custom data attribute, if the total number of characters in the specified inputs is no more than 20.
When the maximum number of characters is reached then we stop saving the typed in value and revert the value back to our previous save (i.e. less than the maxiumum) effectively undo-ing the value.
Well it should be easy one: http://jsfiddle.net/4DETE/1/
var textLength =$inputs.eq(0).val().length+$inputs.eq(1).val().length;
if(textLength>=20)
return false
just count length of values, if you'll have more elements to limit, use jquery.each to iterate inputs
I doubt you can do $inputs.getLength() as $inputs is an array and thus will return the arraylength: 2
You will have to add up the overall sign length in both inputs:
$('#left,#right').keydown(function(){
var leftlength = $('#left').val().length;
var rightlength = $('#right').val().length;
if(leftlength + rightlength > 20)
{
return false;
}
});
or to make it shorter
if($('#left').val().length+$('#right').val().length >20){return false;}

keypress, keyup or keydown only work on the first ring in JQM

in my project have a jQuery Mobile textarea called "topic" on one page
I have this script I am using to count the characters entered in the textarea, but this script just gives me a result on the first keystroke. the other does not.
$(document).delegate("#topicDialog", "pageinit", function() {
$("#topic").keyup(function(e) {
var tam = $(this).length;
if (tam <= 61700){
$("#maxCarac").html(tam +" typed characters. The maximum allowed is 61700");
} else {
alert("You have reached the maximum text size.\nPlease break your text into more than one topic.");
$("#topic").val($("#topic").substring(61700));
}
});
});
example in action
What can be happening?
you need to use val().length
check the update fiddle here
$("#topic").keyup(function(e) {
var tam = parseInt($(this).val().length);
if (tam <= 61700){
$("#maxCarac").html(tam +" typed characters. The maximum allowed is 61700");
} else {
alert("You have reached the maximum text size.\nPlease break your text into more than one topic.");
$("#topic").val($("#topic").substring(61700));
}
});
http://jsfiddle.net/manishkumarshr/zdEzk/1/
this line needs to be changed
var tam = $(this).val().length;
See Demo
You are retrieving incorrectly the length of the user input. Use this:
var tam = $(this).val().length;
Here a working demo.

Categories