Javascript word count on page load not keyup - javascript

I have a little bit of javascript that counts the amount of words on a box. The javascript looks like this:
<script type="text/javascript">
function cnt(w,x){
var y=w.value;
var r = 0;
a=y.replace(/\s/g,' ');
a=a.split(' ');
for (z=0; z<a.length; z++) {if (a[z].length > 0) r++;}
x.value=r;
if (r > 60) {
x.value='Please reduce the word count';
}
}
</script>
and the form like this:
<label>Free brochure from entry:</label>
<textarea name="freebrochureentryform" id="freebrochureentryform" onKeyUp="cnt(this,document.brochure.c)"><?php echo $row['freebrochureentryform']; ?></textarea>
<label>Brocure Entry Word Count:</label>
<input type="text" name="c" value="0" size="20" onKeyUp="cnt(document.brochure.freebrochureentryform,this)" />
Basically the bottom input field shows the amount of words in the upper one. But it only does so when you click on the upper box "freebrochureentryform", but i want it to load the amount of words as soon as the page loads not when you click the box. I guess it is to do with
onKeyUp="cnt(document.brochure.freebrochureentryform,this)"
But have no idea what to change it to.
(Btw way Brochure is the name of my form.)
Any help greatly appreciated.
Ian

You can call the cnt() function on window.onload event.
And instead of listening to onkeyup event, you can listen to the more appropriate oninput (or onpropertychange for IE) event:
JSFiddle
<label>Free brochure from entry:</label>
<textarea name="freebrochureentryform" id="freebrochureentryform">Lorem Text</textarea>
<br />
<label>Brocure Entry Word Count:</label>
<input type="text" name="c" id="c" value="0" size="20" />
window.onload=function(){
function cnt(area,output){
var txt=area.value.replace(/^\s+|\s+$/g,"").replace(/\s+/g," ").split(" ");
if(txt.length>10){
output.value="Please delete some word";
}else{
output.value=txt.length;
}
}
var textarea=document.getElementById("freebrochureentryform");
var info=document.getElementById("c");
if("addEventListener" in window){
if("oninput" in textarea){
textarea.addEventListener("input",function(){
cnt(textarea,info);
},false);
}else if("onpropertychange" in textarea){
textarea.addEventListener("propertychange",function(e){
if((e||event).propertyName=="value"){
cnt(textarea,info);
}
},false);
}else{
textarea.addEventListener("change",function(){
cnt(textarea,info);
},false);
}
}else{
textarea.attachEvent("onpropertychange",function(){
if(event.propertyName=="value"){
cnt(textarea,info);
}
});
}
cnt(textarea,info);
};
Some instruction:
var txt=area.value
.replace(/^\s+|\s+$/g,"") means to trim;
.replace(/\s+/g," ") combines series of white spaces (including line feeds) into one (to better split without the need to iterate the splitted array);
.split(" ") split by white space (as you have already done).
oninput is introduced in IE9 but has some buggy behavior, so you may want to try onproperychange first;
putting function cnt() and textarea/info in window.onload makes them "safe" inside the closure. They can't pollute the global namespace, and things in global namespace can not pollute them.

try to call cnt(w,x) on body onload event

onKeyUp triggers only on User Interaction.
If you load the side there is no Event KeyUp
so instead. Trigger it manually.
call cnt(document.brochure.freebrochureentryform,document.brochure.c) on your body manually (or onload)

function countWords(str) {
let arr = str.split(' ');
let count = 0;
if(arr.length > 0){
for (let i = 0; i< arr.length - 1; i++){
let sentence = arr[0];
let bool = true;
for(let j = 0; j < sentence.length - 1; j++){
let charcode = arr[i].charCodeAt(j);
if((charcode > 64 && charcode < 91) || (charcode > 96 && charcode < 123)){
bool = false;
}
}
if(bool == true){
count += 1;
}
}
}
return arr.length - count;
}
//function calling
countWords("he is a good programer, he won 865 competitions, but sometimes he dont.
what do you think? all test-cases should pass. done-done?");

Related

How to validate texarea by max value using Javascript

I need to validate text area as following code,
my code as follows, here I need set maximum length as 10 and, if user trying to enter more than 10 need to prevent and if it is backspace or delete need to allow for deleting purpose. and also need to show remaining character count in a paragraph. But this code not working well. Its not preventing text input after 10.
<textarea id="txtxasa" class="message-content" onkeyup="Validate(event,this)"></textarea>
<p id="MsgContentRemainingLimit" class="message-character-limit">10 characters remaining</p>
function Validate(e,vald) {
var code;
var txtLength = vald.value.length;
var remainingContent = 10 - txtLength;
$('#MsgContentRemainingLimit').text(remainingContent);
console.log(vald.value.length)
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if (txtLength >=10 && (code != 8 || code != 46))
return false;
}
Have you tried adding maxlength="10" to the textarea. I've done it and it works for me.
In Javascript you can try like this
let element = document.getElementById('input-name');
let countElem = document.getElementById('counter').innerHTML;
element.addEventListener('input', function() {
let inputvalue = this.value;
let maxLength = 10;
//disable the input if reached the limit
if (inputvalue.length > maxLength) {
console.log('maximum character limit reached');
this.disabled = true;
}
//count the numbers
let count = parseInt(countElem, 10);
document.getElementById('counter').innerHTML = count - inputvalue.length;
if (inputvalue.length > count) {
document.getElementById('counter').innerHTML = 0;
}
});
<p>
<input placeholder="First Name" id="input-name" name="input">
</p>
<p>remaining characters:</p><span id="counter" style="font-size:25px; font-weight:600;">10</span><br>
In Html5 you can also use the <input maxlength='10'> to limit characters only as a frontend validation. onkeyup in your code will not work if the user copy text and right click and paste them.

JavaScript with jQuery script not loading

My script with jQuery isn't loading, and when I press the calculate button it doesn't nothing (unsurprisingly.) I KNOW I copied and pasted jQuery in hard code into the file; this is intentional as I want the file to run offline as that's when I normally run it. Also it's intentional that I created the personal console as I normally work on this on a school laptop because that's when I'm bored and they've disabled the developer console.
It's not the jQuery that isn't loading though; I've been able to run it before.
I've tried checking the code, but to me it's just broken. Before the script didn't load, however, I think that somewhere there's an infinite loop because according to task manager, when the script loads and a calculate button is pressed the page freezes but the CPU is running like crazy. I have no idea what could be causing all of this, please help!
I know that other people have probably already done this and that there's probably many other better ways to do what I want to do, so just please remember that I'm doing this for fun, but I've been going at this in my spare time for quite a while an I haven't found anything so either I'm really dumb or the code is broken and it needs a rewrite.
It's supposed to increase the limit of the maximum number a language can understand by pushing the limit from something like 54 billion to 54 billion digits long. However, as stated in the summery, the script doesn't load.
<span id="console"></span>
<form>
<input type="radio" id="add" name="mathtype" checked="checked"> Addition (in devolopment)<br>
<input type="radio" id="sub" name="mathtype"> Subtraction (Unavailible)<br>
<input type="radio" id="multi" name="mathtype"> Multiplication (Unavailible)<br>
<input type="radio" id="div" name="mathtype"> Division (Unavailible)
</form>
<br>
Number: <input type="text" id="input1">
<br>
Number: <input type="text" id="input2">
<br>
<span id="extraInputs"></span>
<button id="addInput">Add another input field</button>
<br>
<button id="calc">Calculate...</button>
<br>
<br>
<p id="output">Press "Calculate..."</p>
<script>/*This is where I load the jQuery*/</script>
<script>
document.getElementById("console").innerHTML("<div class='info'>Script ran</div>");
"use strict";
$(document).ready(function(){
try {
var page = $("#console");
var log = function(message) {
page.append('<div class="log">'+message+'</div>');
};
var info = function(message) {
page.append('<div class="info">'+message+'</div>');
};
var warn = function(message) {
page.append('<div class="warn">'+message+'</div>');
};
var error = function(message) {
page.append('<div class="error">'+message+'</div>');
};
log("Doc and console up");
} catch(err) {
document.getElementById("console").innerHTML("<div class='error'>ERROR WITH LAUNCHING CONSOLE.</div>");
}
try {
var inputBoxes = 2;
var add = function(num1, num2) {
log("Running add");
var neg = [0, false, false];
num1 = num1.split("-");
num2 = num2.split("-");
log(num1);
log(num2);
if(num1.length == 2) {
num1 = num1[1];
neg[1] = true;
} else {
num1 = num1.toString();
}
if (num2.length == 2) {
num2 = num2[1];
neg[2] = true;
} else {
num2 = num2.toString();
}
log(num1);
log(num2);
info(neg);
var isNeg = false;
if(((neg[1] || neg[2]) && (neg[1]!=neg[2])) == true) {
isNeg = true;
}
log(neg);
num1 = num1.split('');
num2 = num2.split('');
log(num1);
log(num2);
var maxChar = Math.max(num1.length, num2.length);
log(maxChar);
if(maxChar > num1.length) {
for(var i=0;i<maxChar-num1.length;i++) {
num1.unshift("0");
}
} else if (maxChar > num2.length) {
for(var i=0;i<maxChar-num1.length;i++) {
num2.unshift("0");
}
}
var final = [];
var time;
var carry = 0;
for (var i=maxChar; i>0;i--) {
if(time != i++) {
carry = 0;
}
final[i] = (parseInt(num1[i]) + parseInt(num2[i]) + parseInt(carry)).toString();
if(parseInt(final[i]) > 9) {
var temp = final[i].split('');
final[i] = temp[1];
carry = temp[0];
time = i;
}
}
if(isNeg){
final.unshift("-");
}
info(final.join());
return final.join();
};
$("button#addInput").click(function(){
inputBoxes++;
$("#extraInputs").append('Number: <input type="text" id="input'+inputBoxes+'"><br>');
});
$("#calc").click(function(){
info("Checking conditions...");
if ($("#add").is(":checked")) {
info("Running...");
info($("#input1").val());
info($("#input2").val());
var final = add($("#input1").val(), $("#input2").val());
info("Ran");
if (inputBoxes > 2) {
info("inputBoxes: "+inputBoxes.toString());
for (var i=3; i<inputBoxes; i++) {
final = add(final, $("#input"+i.toString()).val());
}
}
info(final);
$("#output").text(final));
}
log("Functions up");
});
} catch(err) {
error(err);
}
});
</script>
It should take any amount of numbers and add them (as well as other things eventually), as long as the result's number of characters is less than or equal to the biggest number the language can understand.
I don't know what your code does, but you definitely have an infinite loop here:
for (var i=maxChar; i>0;i--) {
if(time != i++) {
carry = 0;
}
At each iteration, the for loop will decrease i by 1, but you are also increasing it by one, so it will keep the same value and the loop never ends. I imagine you actually wanted to check if (time != i+1).

Javascript - simple counting

This is my first post and second day with Javascript ;). I try to create a simple form, which:
Allows user put any letter / letters in an input field.
Than I want to send it to my script and:
a) check if anything was given in a form
b) if the user put any sign i want to put it in an array and count up the number of tries
c) if the number of tries reach 10 I want to to stop the script
My script doesn't remeber the number of tries. Moreover, it saves the data in an array but after the script is done it erases everything (I put some console.log() in the script, to see if it does anything). It looks like my variable count doesn't remember the number of tries :(.
How can I fix it ? - but in a simple way of coding :) (I don't want to do a lot of changes in my code)
<script type= "text/javascript">
var given_letters = []; // create an empty array
function givenLetter() {
var count = 0;
var max_count = 10;
var letter = document.getElementById('letter').value;
while (count < max_count) {
if (letter === "") {
alert("No letter given");
return false;
} else {
count++;
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(count); // returns "1"
alert("OK");
return true;
}
}
while (count === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
</script>
// in BODY section
<div>
<form><p>Put your letter here: <input type="text" id="letter" size="5" required><button onclick="givenLetter();">Send</button></p></form>
</div>
You can use given_letters.length instead of count, less code and its the same value, you need to use e.preventDefault(); so the form doesnt submit the form yet, here its a working example, for e.preventDefault(); to work you need to send the event in the button, like this:
<div>
<form>
<p>Put your letter here: <input type="text" id="letter" size="5" required>
<button onclick="givenLetter(event);">Send</button></p>
</form>
</div>
the JS updated:
var given_letters = []; // create an empty array
function givenLetter(e) {
e.preventDefault();
var max_count = 10;
var letter = document.getElementById('letter').value;
while (given_letters.length <= max_count) {
if (letter === "") {
alert("No letter given");
return false;
}
else {
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(given_letters.length);//here is your count already
alert("OK");
return true;
}
}
while (given_letters.length === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
The default behaviour of a button in a form is to submit the form... and reload the page (quite stupid, IMO). This is why your script doesn't seem to remember anything. But there's a way to prevent that.
Also, write var count = 0; outside the function, otherwise it's being set to 0 every time the function is called.
var count = 0;
function givenLetter(event) {
event.preventDefault();
// ....
Try this.
Since the button i within the form tag the default behavior of button is submit. so the form will be submitted and reload the page. So to prevent that behavior we use event.preventDefault(); and make count as a global variable.
var given_letters = []; // create an empty array
var count = 0;
function givenLetter() {
event.preventDefault(); //to prevent reloading the page.
var max_count = 10;
var letter = document.getElementById('letter').value;
while (count < max_count) {
if (letter === "") {
alert("No letter given");
return false;
}
else {
count++;
given_letters.unshift(letter);
console.log(letter); // returns letter
console.log(given_letters); // returns array with 1 element
console.log(count); // returns "1"
alert("OK");
return true;
}
}
while (count === max_count) {
alert("Sorry. You exceeded the limit of tries.");
return false;
}
}
<div>
<form>
<p>Put your letter here: <input type="text" id="letter" size="5" required>
<button onclick="givenLetter();">Send</button></p></form>
</div>

Character Counter for multiple text areas

I have a form that has 3 text areas, a copy button, and a reset button. I want to add all the characters to one sum, then display that sum next to the copy/reset button. There is a 500 character limit, and the counter should start at 49 characters. Should I just take all my textareas and "Funnel" them into a var, then count that var? I'm not sure how I should approach this. I've tried this technique
but it only works with one text area, not the sum of all. If the char count goes above 500, I'd like the text to turn red and say "you've gone over your character limit." I do not want to restrict or limit the text once its over 500. I'm a little fried trying to find a solution, and I'm an obvious html/javascript novice.
I do not need to worry about the carriage return issue in firefox/opera since everyone will be using IE11.
<h1>
Enter your notes into the text boxes below
</h1>
<p>
Please avoid using too many abbreviations so others can read your notes.
</p>
<form>
<script type="text/javascript"><!--
// input field descriptions
var desc = new Array();
desc['kcall'] = 'Reason for Call';
desc['pact'] = 'Actions Taken';
desc['mrec'] = 'Recommendations';
function CopyFields(){
var copytext = '';
for(var i = 0; i < arguments.length; i++){
copytext += desc[arguments[i]] + ': ' + document.getElementById (arguments[i]).value + '\n';
}
var tempstore = document.getElementById(arguments[0]).value;
document.getElementById(arguments[0]).value = copytext;
document.getElementById(arguments[0]).focus();
document.getElementById(arguments[0]).select();
document.execCommand('Copy');
document.getElementById(arguments[0]).value = tempstore;
document.getElementById("copytext").reset();
}
--></script>
<p> Reason For Call: </p> <textarea rows="5" cols="40" id="kcall"></textarea><br>
<p> Actions Taken: </p> <textarea rows="5" cols="40" id="pact"></textarea><br>
<p> Recommendations: </p> <textarea rows="5" cols="40" id="mrec"></textarea><br>
<br>
<button type="button" onclick="CopyFields('kcall', 'pact', 'mrec');">Copy Notes</button>
<input type="reset" value="Reset"/>
</form>
I think this question is a little more tricky that you think, and is not cause the complex of count the number of character inside of a textarea thats is actually pretty simple. in jquery:
$("textarea").each(function(index, item){
sum += $(this).val().length;
});
The problem begins whit the keyup event since and how you manage that event, in my follow example, I pretty much manage when the user press the key like in regular state but if you start holding a key then stoping and copy and paste really quick, the event get lost a little bit and recover after the second keyup. Any way here is my full example with count of character counter, change from red to black and black to red if you over pass the max characters and validation for submit or not the form
Fiddle:
https://jsfiddle.net/t535famp/
HTML
<textarea></textarea>
<textarea></textarea>
<textarea></textarea>
<button class="reset"></button>
You have use <span class="characters"></span> of <span class="max"></span>
<button class="submit">submit</button>
JS
$(function(){
var counter = 0; //you can initialize it with any number
var max = 400; //you can change this
var $characters = $(".characters");
var $max = $(".max");
var submit = true;
$characters.html(counter);
$(".max").html(max);
function count(event){
var characters = $(event.target).val().length;
$characters.html(counter);
//sum the textareas
var sum = 0;
$("textarea").each(function(index, item){
sum += $(this).val().length;
});
counter = sum;
if(counter > max) {
$characters.css({ color : "red" });
submit = false;
}else{
$characters.css({ color : "black" });
submit = true;
}
}
$(document).on("keyup","textarea",count);
$(document).on("click",".submit",function(){
if(submit)
alert("done");
else
alert("you have more characters than " + max);
});
})
Good luck my 2 cents
function textareaLength() {
var charCount = 0;
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (textarea) { charCount += textarea.value.length; });
return charCount;
}
That will return the count of all textareas on the page. Change the querySelector to be more specific if you only want to count specific textareas.
One option would be to add onchange events to your textareas which call a function like below:
<script>
function validate() {
if(textareaLength() >= 500) {
//limit reached
}
}
function textareaLength() {
var charCount = 0;
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (textarea) { charCount += textarea.value.length; });
return charCount;
}
</script>
<textarea onchange="validate()"></textarea>
<textarea onchange="validate()"></textarea>
<textarea onchange="validate()"></textarea>
Count
Here's a really simple function:
function TextLength() {
return Array.prototype.reduce.call(
document.querySelectorAll('textarea'),
function(b,a) { return b+a.value.length }, 0);
}
Or with ES6:
const TextLength = () => Array.from(document.querySelectorAll('textarea')).reduce((b,a) => b + a.value.length, 0)
To use this:
TextLength();
Change
Now add this:
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (e) { e.oninput = TextLength });
And again, ES6:
Array.from(document.querySelectorAll('textarea')).forEach(e => e.oninput = TextLength );
Since the button is in the same form as the textarea elements, you can get a reference to the form using the button's form property. You can also get all the text area elements in the form using querySelectorAll, then loop over them, adding up the characters in each.
The following just counts the total number of characters in the textarea elements:
<button type="button" onclick="count(this)">Copy Notes</button>
and the function:
function count(el) {
var tas = el.form.querySelectorAll('textarea');
var numChars = 0;
for (var i=0, iLen=tas.length; i<iLen, I++) {
numChars += tas[i].value.length;
}
return numChars;
}
If you can rely on ES5+ methods, then you can do:
function count(el) {
return Array.prototype.reduce.call(el.form.querySelectorAll('textarea'),
function(numChars, ta){return numChars += ta.value.length}, 0);
}
Note that by convention, functions starting with a capital letter are reserved for constructors, so CopyFields should be copyFields.
Here's a working example:
function count(el) {
return Array.prototype.reduce.call(el.form.querySelectorAll('textarea'),
function(numChars, ta){return numChars += ta.value.length}, 0);
}
<form>
<textarea name="ta0"></textarea>
<textarea name="ta1"></textarea>
<textarea name="ta2"></textarea><br>
<input type="text" name="numChars">
<button type="button" onclick="this.form.numChars.value = count(this)">count</button>
<input type="reset">
</form>
If you have more than one textarea (Multiple) and you want to display character count on each textarea, you may try below code, as its working me like a charm.
$(document).ready(function () {
$('textarea').on("load propertychange keyup input paste",
function () {
var cc = $(this).val().length;
var id=$(this,'textarea').attr('id');
$('#'+id).next('p').text('character Count: '+cc);
});
$('textarea').trigger('load');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id="one">hello</textarea>
<p></p>
<textarea id="two"></textarea>
<p></p>
<textarea id="three"></textarea>
<p></p>

Comparing two input fields

I have this function which i am using to compare two input fields. If the user enters the same number in both the text field. On submit there will be an error. Now i would like to know if there is a way to allow same number but not higher than or lower the value of the previous text box by 1. For example if user enters 5 in previous text box, the user can only input either 4, 5 or 6 in the other input field.Please give me some suggestions.
<script type="text/javascript">
function Validate(objForm) {
var arrNames=new Array("text1", "text2");
var arrValues=new Array();
for (var i=0; i<arrNames.length; i++) {
var curValue = objForm.elements[arrNames[i]].value;
if (arrValues[curValue + 2]) {
alert("can't have duplicate!");
return false;
}
arrValues[curValue] = arrNames[i];
}
return true;
}
</script>
<form onsubmit="return Validate(this);">
<input type="text" name="text1" /><input type="text" name="text2" /><button type="submit">Submit</button>
</form>
A tidy way to do it which is easy to read:
var firstInput = document.getElementById("first").value;
var secondInput = document.getElementById("second").value;
if (firstInput === secondInput) {
// do something here if inputs are same
} else if (firstInput > secondInput) {
// do something if the first input is greater than the second
} else {
// do something if the first input is less than the second
}
This allows you to use the values again after comparison as variables (firstInput), (secondInput).
Here's a suggestion/hint
if (Math.abs(v1 - v2) <= 1) {
alert("can't have duplicate!");
return false;
}
And here's the jsfiddle link, if you want to see the answer
Give them both IDs.
Then use the
if(document.getElementById("first").value == document.getElementById("second").value){
//they are the same, do stuff for the same
}else if(document.getElementById("first").value >= document.getElementById("second").value
//first is more than second
}
and so on.

Categories

Resources