Why is my character counter not excluding spaces? - javascript

I am making a character counter with HTML, CSS, JS. I got the counter working, but I have a checkbox that should get the length of the input without the spaces, but it is not working. Please check my code and tell me what's wrong.
function char_count(str, letter) {
var letter_Count = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == letter) {
letter_Count += 1;
}
}
return letter_Count;
}
function countChars(obj) {
var length = obj.value.length;
var output = document.getElementById("chars");
var dis = document.getElementById("removeSpace");
if (dis.checked) {
var spaces = char_count(obj, " ");
length = length - spaces;
output.innerHTML = length + ' characters';
} else {
output.innerHTML = length + ' characters';
}
}
<h1> Character Counter </h1>
<textarea id="input" onkeyup="countChars(this)" placeholder="Enter your text here..." autofocus></textarea>
<input type="checkbox" id="removeSpace">
<label for="removeSpace" onclick="countChars(document.getElementById('input'))">Don't Include Spaces</label>
<span id="chars">0 Characters</span>

You could make the code more simpler. Moreover, you have placed the checkbox outside the label that has onclick="countChars(document.getElementById('input'))", that's why the condition dis.checked in js does not find the checkbox as checked. Place the checkbox inside the label.
The whole simplified code would be like this,
<h1> Character Counter </h1>
<textarea id="input" onkeyup="countChars(this)" placeholder="Enter your text here..." autofocus></textarea>
<label for="removeSpace" onclick="countChars(document.getElementById('input'))">
<input type="checkbox" id="removeSpace">
Don't Include Spaces</label>
<span id="chars">0 Characters</span>
<script>
function countChars(obj) {
var length = obj.value.length;
var output = document.getElementById("chars");
var dis = document.getElementById("removeSpace");
if (dis.checked) {
length = obj.value.replace(/\s/g, '').length
}
output.innerHTML = length + ' characters';
}
</script>

Related

Can't get this javascript (Luhn Algorithm) to work in this perl CGI file

I have a shopping cart that doesn't validate cards and I'm getting a lot of declined orders because people don't catch their typos. Trying to add Luhn validation to it.
I found this script which works fine by itself. It on-the-fly changes invalid to valid when a "good" credit card number is typed in.
<input id="cc" type="text" name="creditcard" size="20"><p id="status">invalid</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('#cc').on('input', function(){
if (checkLuhn($('#cc').val())) {
$('#status').html('valid');
} else {
$('#status').html('invalid');
}
});
function checkLuhn(value) {
// remove all non digit characters
var value = value.replace(/\D/g, '');
var sum = 0;
var shouldDouble = false;
// loop through values starting at the rightmost side
for (var i = value.length - 1; i >= 0; i--) {
var digit = parseInt(value.charAt(i));
if (shouldDouble) {
if ((digit *= 2) > 9) digit -= 9;
}
sum += digit;
shouldDouble = !shouldDouble;
}
return (sum % 10) == 0;
}
</script>
I'm trying to insert it into the HTML portion of the CGI file, below this relevant line and giving the INPUT the id="cc" tag, but the script won't run.
<INPUT TYPE="text" id="cc" NAME="Payment_Card_Number" MAXLENGTH="20" size="20" value="$form_data{'Payment_Card_Number'}">

Find the word after specific word

i am new in javascript.
I have below code where textarea contains text as...
<textarea id="myBox" >
{Picker:} Helper
This is just demo...
</textarea>
<br/>
<span id="ans"></span> <br/>
<input type="button" onclick="getWord()" value="Click"/>
i am trying to find out the word exact after the {Picker:}, i.e. i want to find word "Helper". So word {Picker:} is the point from where i am starting to find immediate word after it. For this i using indexOf. What i did uptil now is ...
<script>
function getWord() {
var val = $("#myBox").val();
var myString = val.substr((val.indexOf("{Picker:}")) + parseInt(10), parseInt(val.indexOf(' ')) );
$("#ans").text(myString);
}
</script>
will anyone guide me to find what mistake i am making. Thanks in advance.
You should start from the index of "{Picker:}" + 9, because the length of the particular string is 9.
Parse till the the index of '\n' which is the line break character.
String.prototype.substr() is deprecated, use String.prototype.substring() instead.
function getWord() {
var val = $("#myBox").val();
var myString = val.substring((val.indexOf("{Picker:}")) + 9, val.indexOf('\n'));
$("#ans").text(myString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<textarea id="myBox">
{Picker:} Helper
This is just demo...
</textarea>
<br />
<span id="ans"></span> <br />
<input type="button" onclick="getWord()" value="Click" />
var val = $("#myBox").val();
console.log(val)
var tempArray = val.replace("\n", " ").split(" ");
var wordToFind;
for(var i = 0 ; i < tempArray.length; i++) {
var word = tempArray[i];
if (word == "{Picker:}") {
wordToFind = tempArray[i + 1]
}
}
console.log(wordToFind)
This will assign what ever word comes after Picker: to the wordToFind variable.
Check working :https://jsfiddle.net/o5qasnd0/14/
You could do something like this
const text = "{Picker:} Helper";
const wordArr = text.split(' ');
const idx = wordArr.indexOf('{Picker:}');
console.log(idx != -1 && (idx + 1) < wordArr.length ? wordArr[idx + 1] : 'not found');

How to find if there is a space in a string... tricky

I'm doing this for a school project but one thing is bugging me, there is a part of the project that requires me to change white space or just " " a space to a number. Here is my code:
I know its messy, I've only been coding for half a year
exclsp is "exclude spaces"
inclsp is "include spaces"
dispwos is "display without spaces"
dispwsp is "display with spaces"
var txt;
var num;
var spce = 0;
function cnt()
{
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked === true)
{
for (var i = 0; i < num; i++) {
if (txt.includes(" "))
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
}
}
document.getElementById("dispwos").innerHTML = num - spce + " characters.";
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="LetterCount.js"></script>
<link rel="stylesheet" type="text/css" href="LetterCount.css"/>
<title>Letter Counter</title>
</head>
<body>
<textarea rows="4" cols="50" placeholder="Input your text here!" id="disp"></textarea><br>
<form name="form1">
<input type="radio" name="button" id="inclsp"> Include spaces</input><br>
<input type="radio" name="button" id="exclsp"> Exclude spaces</input><br>
</form>
<button onclick="cnt()">Click Me!</button><br><br>
<div id="dispwsp"></div>
<div id="dispwos"></div>
</body>
</html>
I think you need to change this line:
if (txt.includes(" "))
to
if (txt[i] == " ")
so that you're actually checking each character rather that attempting to examine the whole string each time.
You could also use a regular expression and do it in one simple line of code and eliminate the loop altogether:
spce = txt.match(/\s/g).length
I don't understand the purpose of the dispwsp dispwos so I just removed them. You only have 1 result you want to display so why put it in different places just make one div for your result, like
<div id="result"></div>
And your JS can be simplified a lot, you don't need to loop through the letters. Here's the fiddle: https://jsfiddle.net/zwzqmd27/
function cnt() {
var inputText = document.getElementById("disp").value;
if (document.getElementById("exclsp").checked) //exclude spaces
{
document.getElementById("result").innerHTML = inputText.split(" ").join("").length + " characters";
}
else //include spaces
{
document.getElementById("result").innerHTML = inputText.length + " characters";
}
}
Possible duplicate of Check if a string has white space
But you can try this.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
If You want to change a white space in a string to a number..
This could possibly help you ...
str.replace(/\s/g,"9");//any number(that You want)
This piece of code is basically replaces the white space with a number..
As #Micheal said, you can use indexOf() method to check if particular character(s) is present in your text content.
You just need to pass the character or substring(set of characters) to check if it is present.
Example :
var myText = "Sample text";
var substringIndex = myText.indexof(" "); //substringIndex = 6
substringIndex = mytext.indexof("ex");//substringIndex = 8;
substringIndex = mytext.indexof("tt"); // substringIndex =-1;
If substring doesn't matches, it will return -1 as index.
By using index you can say, if particular character(substring) presents if index value is greater than -1.
Note : If u pass set of characters, it will return only the starting index of the first character if entire set matches.
In your case, it would be like
...........
...........
if (txt.indexOf(" ")>-1)
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
...............
...............
Just replace script with code bellow..
I do it for you...
var txt;
var num;
var spce = 0;
function cnt()
{
//to clear "dispwsp" and "dispwos" before action in cnt() function
document.getElementById("dispwsp").innerHTML = "";
document.getElementById("dispwos").innerHTML = "";
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked == true)
{
num = 0;
spce = 0;
for (var i = 0; i < txt.length; i++) {
var temp = txt.substring(i, (i+1));
if(temp==" ")
{
spce++;
}else
{
num++;
}
document.getElementById("dispwos").innerHTML = num + " characters and "+ spce +" spces ";
}
}
}

Limiting character in textbox input

please be nice. I'm trying to create a page which sets limit and cut the excess (from the specified limit). Example: Limit is 3. then, I'll input abc if I input d it must say that its limit is reached and the abc will remain. My problem is that it just delete my previous input and make new inputs. Hoping for your great cooperation. Thanks.
<html>
<script type="text/javascript">
function disable_btn_limit(btn_name)
{
/* this function is used to disable and enable buttons and textbox*/
if(btn_name == "btn_limit")
{
document.getElementById("btn_limit").disabled = true;
document.getElementById("ctr_limit_txt").disabled = true;
document.getElementById("btn_edit_limit").disabled = false;
}
if(btn_name == "btn_edit_limit")
{
document.getElementById("btn_limit").disabled = false;
document.getElementById("ctr_limit_txt").disabled = false;
document.getElementById("btn_edit_limit").disabled = true;
}
}
function check_content(txtarea_content)
{
/*This function is used to check the content*/
// initialize an array
var txtArr = new Array();
//array assignment
//.split(delimiter) function of JS is used to separate
//values according to groups; delimiter can be ;,| and etc
txtArr = txtarea_content.split("");
var newcontent = "";
var momo = new Array();
var trimmedcontent = "";
var re = 0;
var etoits;
var etoits2;
//for..in is a looping statement for Arrays in JS. This is similar to foreach in C#
//Syntax: for(index in arr_containter) {}
for(ind_val in txtArr)
{
var bool_check = check_if_Number(txtArr[ind_val])
if(bool_check == true)
{
//DO NOTHING
}
else
{
//trim_content(newcontent);
newcontent += txtArr[ind_val];
momo[ind_val] = txtArr[ind_val];
}
}
var isapa = new Array();
var s;
re = trim_content(newcontent);
for(var x = 0; x < re - 1; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
}
function trim_content(ContentVal)
{
//This function is used to determine length of content
//parseInt(value) is used to change String values to Integer data types.
//Please note that all value coming from diplay are all in String data Type
var limit_char =parseInt(document.getElementById("ctr_limit_txt").value);
var eto;
if(ContentVal.length > (limit_char-1))
{
alert("Length is greater than the value specified above: " +limit_char);
eto = limit_char ;
etoits = document.getElementById("txtarea_content").value;
//document.getElementById("txtarea_content").value = "etoits";
return eto;
//for(var me = 0; me < limit_char; me++)
//{document.getElementById("txtarea_content").value = "";}
}
return 0;
}
function check_if_Number(ContentVal)
{
//This function is used to check if a value is a number or not
//isNaN, case sensitive, JS function used to determine if the values are
//numbers or not. TRUE = not a number, FALSE = number
if(isNaN(ContentVal))
{
return false;
}
else
{ alert("Input characters only!");
return true;
}
}
</script>
<table>
<tr>
<td>
<input type="text" name="ctr_limit_txt" id="ctr_limit_txt"/>
</td>
<td>
<input type="button" name="btn_limit" id="btn_limit" value="Set Limit" onClick="javascript:disable_btn_limit('btn_limit');"/>
</td>
<td>
<input type="button" name="btn_edit_limit" id="btn_edit_limit" value="Edit Limit" disabled="true" onClick="javascript:disable_btn_limit('btn_edit_limit');"/>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtarea_content" id="txtarea_content" onKeyPress="javascript:check_content(this.value);"></textarea>
<br>
*Please note that you cannot include <br>numbers inside the text area
</td>
</tr>
</html>
Try this. If the condition is satisfied return true, otherwise return false.
<html>
<head>
<script type="text/javascript">
function check_content(){
var text = document.getElementById("txtarea_content").value;
if(text.length >= 3){
alert('Length should not be greater than 3');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div>
<textarea name="txtarea_content" id="txtarea_content" onkeypress=" return check_content();"></textarea>
</div>
</body>
</html>
Instead of removing the extra character from the text area, you can prevent the character from being written in the first place
function check_content(event) { //PARAMETER is the event NOT the content
txtarea_content = document.getElementById("txtarea_content").value; //Get the content
[...]
re = trim_content(newcontent);
if (re > 0) {
event.preventDefault(); // in case the content exceeds the limit, prevent defaultaction ie write the extra character
}
/*for (var x = 0; x < re - 1; x++) {
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}*/
}
And in the HTML (parameter is the event):
<textarea ... onKeyPress="javascript:check_content(event);"></textarea>
Try replacing with this:
for(var x = 0; x < re - 6; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
Any reason why the maxlength attribute on a text input wouldn't work for so few characters? In your case, you would have:
<input type="text" maxlength="3" />
or if HTML5, you could still use a textarea:
<textarea maxlength="3"> ...
And then just have a label that indicates a three-character limit on any input.

Grand Total Calculation in Javascript to handle currency format (MinusSignNegative)

I currently have a javascript code below that calculates a grand total into a read only text field when dealing with currency formats i.e. $500.00. The problem that I am running into is how to handle the calculation when more than one negative number is entered in currency format (MinusSignNegative) i.e. ($500.00) instead of -$500.00. I am currently getting a NaN error in the grand total.
I believe that this regex should handle it but I can't figure out how to implement. http://www.regexlib.com/(X(1)A(bk8AHOFYowt7XHOC4WUCtfdM2LhlaovTNInhWLTrzAeoeq-c53XkkdwLD-WDe3OgQtJ7BLHSs0P-u-RrLbfVZaQIHkBH2exYGw0qtz6nqSamZNVqtnyufo9Y3nrEq5mq-mry63HY4Nnv0dfsQOZzKvuwcKAuwigyyQva-67laxr-ModxTQESW8fXx2XJL_0L0))/REDetails.aspx?regexp_id=625&AspxAutoDetectCookieSupport=1
Can anybody offer a solution?
<SCRIPT LANGUAGE="JavaScript">
<!--
function total(what,number) {
var grandTotal = 0;
for (var i=0;i<number;i++) {
if (what.elements['price' + i].value.replace(/\$|\,/g,'') == '')
what.elements['price' + i].value.replace(/\$|\,/g,'') == '0.00';
grandTotal += (what.elements['price' + i].value.replace(/\$|\,/g,'') - 0);
}
what.grandTotal.value = (Math.round(grandTotal*100)/100);
}
//-->
</SCRIPT>
<FORM NAME="myName">
Tax Due/Refund: <input TYPE="text" NAME="price0" VALUE="" SIZE="10" class='currency' onChange="total(this.form,3)"><BR>
Interest: <input TYPE="text" NAME="price1" VALUE="" SIZE="10" class='currency' onChange="total(this.form,3)"><BR>
Penalty: <input TYPE="text" NAME="price2" VALUE="" SIZE="10" class='currency' onChange="total(this.form,3)"><BR>
Total Amount Assessed: <INPUT TYPE="TEXT" NAME="grandTotal" class='currency' SIZE="25" READONLY="readyonly" style="background:#eee none; color:#222; font-weight:bold">
</FORM>
If you are trying to move a negative sign from the number to the left of a dollar sign,
do it when you write the total value field.
function total(what, number){
var grandTotal= 0, i= number, val, sign;
while(i){
val= what.elements['price' + i--].value.replace([$, ]+/g,'') ;
grandTotal+= parseFloat(val) || 0;
}
sign= grandTotal<0? '-' :'';
what.grandTotal.value= sign+'$'+ Math.abs(Math.round(grandTotal*100)/100);
}
You can do it with or without that regex.
Without:
fieldValue = field.value; // "(500.00)"
// search for a "(" char
if (fieldValue.indexOf("(") >= 0) {
// remove all chars, but numbers and dots
fieldValue = fieldValue.replace(/[^0-9.]/ig, "");
// 500.00
numberFieldValue = Number(fieldValue) * -1;
}
With:
fieldValue = field.value; // "(500.00)"
// test if the value matches that pattern for negative numbers
if (fieldValue.match(/PUT_THAT_REGEX_HERE/g)) {
// remove all chars, but numbers and dots
fieldValue = fieldValue.replace(/[^0-9.]/ig, "");
// 500.00
numberFieldValue = Number(fieldValue) * -1;
}
it should look like this:
function total(what,number) {
var grandTotal = 0;
for (var i=0;i<number;i++) {
fieldValue = what.elements['price' + i].value; // "(500.00)"
// search for a "(" char
if (fieldValue.indexOf("(") >= 0) {
// remove all chars, but numbers and dots
fieldValue = fieldValue.replace(/[^0-9.]/ig, "");
// 500.00
numberFieldValue = Number(fieldValue) * -1;
} else if (fieldValue.replace(/\$|\,/g,'') == '') {
numberFieldValue = 0;
} else {
numberFieldValue = number(fieldValue.replace(/\$|\,/g,''));
}
grandTotal += numberFieldValue ;
}
what.grandTotal.value = (Math.round(grandTotal*100)/100);
}

Categories