jQuery > Word counter: Get increasing counter value when deleting words - javascript

I am using textarea to get comments and everything.
Text area that I use has word limits or maxlength of words. Now I will let users know that how many characters you can type more.
Though this is success till now, But i've got a problem in refreshing the counter values. It doesn't show refreshed value of counter as soon as i delete characters.
Also when i do keyup then counter shows old value from where i started deleting characters.
Now if textarea is empty and i type something then counter works good.
I have got a fiddle here-
Text area counter
Steps to reproduce-
Type a longer sentence.
Now delete this sentence from textarea.
Delete all texts from textarea and start typing again, it starts from full length of words.
counter is not showing refreshed values after deleting.
This is some code of jQuery-
$(document).ready(function() {
var text_max = 300;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keypress(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});

It is because you are using keypress, use keyup event.
In Chrome and IE the keypress event will be fired only when keys which can be displayed are pressed. Key like backspace and delete do not have a display property so keypress event will not get fired.
$(document).ready(function() {
var text_max = 300;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});
Demo: Fiddle

I've had this one before!
Trick is to use keyup() instead of keypress()
Fiddle.

Here's how I would do it to capture all changes.
Also, I would change the HTML to have a default of 300 or whatever number to start and then wrap the counter value you are changing in another element and only change its value through this function.
$(document).ready(function() {
//Don't search for it over and over again
var $cachedSelector = $('#textarea_feedback');
var $cachedTextArea = $('#textarea');
//Common function you can call repeatedly that only updates the counter
function changeTextArea(){
var text_length = $cahcedTextArea.val().length;
var text_remaining = 300 - text_length;
$cachedSelector.html(text_remaining);
}
//Handles Keyup or typing events
$cachedTextArea.keyup(function() {
changeTextArea()
});
//Handles common chage events like if someone copy/pastes into your input
$cachedTextArea.change(function() {
changeTextArea()
});
});

Related

js loses chars if typed too quickly

OK, I got this completed and working and I've removed mention of some of the issues I had to assist with easy reading.
I am obfuscating the characters entered to a text box (id='user_pin_code') such that they appear to be ' * ' or ' **** ' according to the number of chars.
It's for the entry of a PIN code.
The first part takes the chars entered and replaces each with an ' * ' asterisk. So a 6 char PIN will show ' ****** '
All good so far, regardless of how quickly I type.
The next part takes the actual chars entered and populates another textbox (id='PINcode'), with the actual characters entered.
Trouble is, if I type quickly some are missed out.
so 'wxymdo' can be entered as 'wxmd'.
<script>
$(document).ready(function(e) {
var actualTextEntered = "";
$("#user_pin_code").keyup(function(e) {
var x = document.getElementById("user_pin_code").value;
actualTextEntered += x.replace(/\\*/g,"");
addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if ( key === "Backspace" ) {
// Do something
actualTextEntered = '';
x='';
}
});
document.getElementById("user_pin_code").value = "";
for (var i=0;i<actualTextEntered.length;i++)
{
document.getElementById("user_pin_code").value += "*";
document.getElementById("PINcode").value = actualTextEntered;
}
});
});
The problem is just how the keyup event works, it tends not to be able capture some very fast inputs. Just the way onmousemove works, when the mouse moves very fast, some element will be skipped.
Why not use input type="password" or I think using oninput event can be a work around for you.

Textarea Character Limit, and Whitespace Trim

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.

Run Function Every Time a Value is Entered or Deleted from a Textarea to Instantly Find Sum

I wrote a simple JavaScript that solves addition problems (1 + 1 OR 1 + 5 + 2 + 9, etc.). It works fine.
The problem is I want it to continuously run as new values are entered. As soon as I type "1 + 1" it should display 2, if I continue to type and type "+ 1" it should display 3 and so on.
The continuously running part works somewhat. If I enter "1 + 1" the sum is not displayed until I press the spacebar --- but it should immediately display 2 without having to press the spacebar. What am I missing?
Fiddle: http://jsfiddle.net/z26eg/
HTML
<textarea cols="50" rows="10" id="addThis"></textarea>
<div id="sum"></div>
JavaScript
var input = document.getElementById("addThis");
input.onkeypress = function() {
var finalAnswer = 0;
// Get form input
var processAddThis = addThis.value;
// Remove all spaces in problem
// Example problem: 10 + 3 + 2
processAddThis = processAddThis.replace(/\s/g,''); // 10+3+2
// Split numbers into an array
var addTheseValues = processAddThis.split("+");
// Go through numbers and add them up
for (var i = 0; i < addTheseValues.length; i++) {
finalAnswer += Number(addTheseValues[i]);
}
// Display sum
sum.innerHTML = finalAnswer;
}
You should use on keyup instead :
http://jsfiddle.net/z26eg/1/
input.onkeyup = function() {
.....
};
You should call the function onkeyup like the below:
input.onkeyup = function() {
/* The rest of your current code as it already works fine */
};
The keydown event occurs when the key is pressed, followed immediately by the keypress event. During both these times, the value of the key that has been pressed is still not available for calculation.
Then the keyup event is generated when the key is released. At this point of time, the value of the key that has been pressed is available for calculation.
In this fiddle, input any value in the textarea and have a look at the console to see the difference between the three events.
Try the 'onkeyup' event. It works for me.

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