Word count jquery and stop user from typing - javascript

$(document).ready(function(){
$("input").keyup(function(){
if($(this).val().split(' ').length == 10){
alert();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Enter your name: <input type="text">
If the input is 1 2 3 4 5 6 7 8 9 the alert fired, I know it included the space. But how to stop user from adding more character (even space) when the limit is reached?

The problem can easily be simplified to disabling the spacebar when the max word count is reached:
this should work: http://jsfiddle.net/wznervgz/6/
<input data-max-words="10" />
js:
$('input[data-max-words]').on('keydown', function (e) {
var $txt = $(this),
max = $txt.data('maxWords'),
val = $txt.val(),
words = val.split(' ').length;
if (words === max && e.keyCode === 32)
return false;
});

Hope this will help you.
<textarea name="txtMsg" id="word_count" cols="1" rows="1"> </textarea>
<span style="padding-left:10px;">Total word Count :
<span id="display_count" style="font-size:16px; color:black;">0</span> words &
<span id="count_left" style="font-size:16px; color:black;">2</span> words left.</span>
<br>
jquery code:
var max_count = 2;
$(document).ready(function () {
var wordCounts = {};
$("#word_count").keyup(function () {
var matches = this.value.match(/\b/g);
wordCounts[this.id] = matches ? matches.length / 2 : 0;
var finalCount = 0;
$.each(wordCounts, function (k, v) {
finalCount += v;
});
var vl = this.value;
if (finalCount > max_count) {
vl = vl.substring(0, vl.length - 1);
this.value = vl;
}
var countleft = parseInt(max_count - finalCount);
$('#display_count').html(finalCount);
$('#count_left').html(countleft);
am_cal(finalCount);
});
}).keyup();
Fiddle link: http://jsfiddle.net/aVd4H/32/
Thank you.

Think about storing the value of the input after each keyup and if the wordcount is greater than your limit just setVal back to the "previously" saved amount. So it would start off as var previousVal = ''; and then increment accordingly until the comparison returns true, set the val and return.
Demo: http://jsfiddle.net/robschmuecker/wznervgz/1/
$(document).ready(function(){
var previousValue = '';
$("input").keydown(function(){
if($(this).val().split(' ').length >= 10){
alert();
$(this).val(previousVal);
return;
}
previousVal = $(this).val();
});
});

You can try this:
$("input").keydown(function(e){
if($(this).val().split(' ').length == 10){
alert();
e.preventDefault();
return false;
}

Related

how to replace input numbers with commas after key presses

I want to replace a number over 100 with commas. Like 1000 to 1,000 and 1000000 to 1,000,000 etc. in HTML. I have found the code on here to do so but it only works with predetermined numbers being passed. I don't want it to work for a predetermined number but for any number typed into the box.
<label for="turnover">Estimated Monthly Card Turnover:</label><br />
<span>£ </span><input type="text" id="turnover" maxlength="11"
name="turnover" size="10" required>*
<br /><br />
<script type="text/javascript">
$('#turnover').keydown(function(){
var str = $(this).val();
str = str.replace(/\D+/g, '');
$(this).val(str.replace(/\B(?=(\d{3})+(?!\d))/g, ","));});
</script>
I created a solution using pure javascript.
function onChange(el) {
var newValue = el.value.replace(/,/g, '');
var count = 0;
const last = newValue.substring(newValue.length - 1, newValue.length); // last input value
// check if last input value is real a number
if (!isNumber(last)) {
el.value = el.value.substring(0, el.value.length - 1);
return;
}
newValue = newValue.split('')
.reverse().map((it) => {
var n = it;
if (count > 0 && count % 3 == 0) n = n + ',';
count++;
return n;
})
.reverse().join('')
el.value = newValue
// document.getElementById('value').innerHTML = newValue
}
function isNumber(input) {
return input.match(/\D/g) == undefined;
}
<label>Number</label>
<input id="numbers" onkeyup="onChange(this)">
There are a couple of issues with your code:
It runs once when the page loads, not after that. I added a button to fix that.
The id used in your code does not match the actual id of the input field.
Input fields must be read and written using .val(). .text() works only for divs, spans etc.
Note that the conversion now works one time, after that it fails to properly parse the new text which now contains the comma(s).
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function ShowComma() {
console.clear();
var val = parseInt($("#comma").val());
console.log(val);
val = numberWithCommas(val);
console.log(val);
$("#comma").val(val);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="turnover">Estimated Monthly Card Turnover:</label><br />
<span>£ </span><input type="value" id="comma" maxlength="30" name="turnover" size="10" required>*
<button onclick="ShowComma()">Show Comma</button>
To finalise this I have putgetElementById functions in so that this will work with a wordpress contact form 7. This must be with a text field though as it will not work with the number field as it will now accept commas:
<script>
document.getElementById("averagetrans").onkeyup = function() {onChange(this)};
document.getElementById("Turnover").onkeyup = function() {onChange(this)};
</script>
<script type="text/javascript">
function onChange(el) {
var newValue = el.value.replace(/,/g, '');
var count = 0;
const last = newValue.substring(newValue.length - 1, newValue.length); // last input value
// check if last input value is real a number
if (!isNumber(last)) {
el.value = el.value.substring(0, el.value.length - 1);
return;
}
newValue = newValue.split('')
.reverse().map((it) => {
var n = it;
if (count > 0 && count % 3 == 0) n = n + ','; // put commas into numbers 1000 and over
count++;
return n;
})
.reverse().join('')
el.value = newValue
// document.getElementById('value').innerHTML = newValue
}
function isNumber(input) {
return input.match(/\D/g) == undefined;
}
</script>

When pressed 'Enter', sum the input and clear it

I'm in the begin fase of learning JS. I'm trying to make a page were the user can put numbers in a text field. The user can press enter to add another number. When the user pressed enter the input field need to be cleared
The amounts entered must be added together and their total must be shown in a second text box.
my HTML:
<input type="text" id="input">
<p>Uw totaal:</p>
<input type="text" id="output">
My JS:
input = document.getElementById("input");
input.onkeypress = function(event) {
ceckKey(event);
};
function ceckKey(e) {
// check for enter: e.key is for Firefox
// if true, make input empty
if (e.keyCode == 13 || e.key == 13) {
input.value = "";
}
var number = +input.value;
return number;
}
var total = 0
total += checkKey();
document.getElementById("output").value = total;
The keypress works in every browser. The problem is that i cannot sum the numbers. If i put it in the keypress function, the number will be cleared everytime you hit enter again.
I hope you guys can help!
Get the value before your clear it.
var input = document.getElementById("input");
var output = document.getElementById("output");
var total = 0;
input.onkeypress = function(e) {
if (e.keyCode == 13 ||  e.key == 13) {
total += +input.value;
output.value = total;
input.value = "";
}
};
<input type="number" id="input">
<p>Uw totaal:</p>
<input type="number" id="output">
Give this a shot -
var total = 0;
input = document.getElementById("input");
output = document.getElementById("output");
input.onkeypress = function(e) {
total = total + input.value * 1;
if(e.keyCode == 13) {
input.value = "";
}
output.value = total;
};
<input type="text" id="input">
<p>Uw totaal:</p>
<input type="text" id="output">
And hey, welcome to JS!
you clear your input field too early.
var number = 0
function ceckKey(e) {
// check for enter: e.key is for Firefox
// if true, make input empty
if (e.keyCode == 13 || e.key == 13) {
number += input.value;
input.value = "";
}
return number;
}
document.getElementById("output").value = number;
note that your number variable may not be declared inside of the checkKey function. Greetings
You are updating the output element outside of the ceckKey function.
This update IS not automatic. You must trigger it.
Also, check carefully that function. Callbacks can return a value but using the dame function for a callbacks and getting that output contents does not look good.
You are clearing the value of input before calculating the total. I have updated your code little bit to work as you intended.
input = document.getElementById("input");
output = document.getElementById("output");
input.onkeypress = function(event) {
checkKey(event);
};
function checkKey(e) {
// check for enter: e.key is for Firefox
// if true, make input empty
if (e.keyCode == 13 || e.key == 13) {
// Note : in the begining the output text box is empty, so while output is empty i have assign 0 as its value.
outputValue = (output.value == '') ? 0 : output.value;
total = parseInt(outputValue) + parseInt(input.value);
input.value = "";
// To update the total in output text box
document.getElementById("output").value = total;
}
}

Formatting number as thousand using only Javascript

Console.log is showing the correct result, but how can I add the same formatting to the input type while typing.
Input type is reset after every comma to zero.
1000 to 1,000
Please Help.
This code is working here
function numberWithCommas(number) {
if (isNaN(number)) {
return '';
}
var asString = '' + Math.abs(number),
numberOfUpToThreeCharSubstrings = Math.ceil(asString.length / 3),
startingLength = asString.length % 3,
substrings = [],
isNegative = (number < 0),
formattedNumber,
i;
if (startingLength > 0) {
substrings.push(asString.substring(0, startingLength));
}
for (i=startingLength; i < asString.length; i += 3) {
substrings.push(asString.substr(i, 3));
}
formattedNumber = substrings.join(',');
if (isNegative) {
formattedNumber = '-' + formattedNumber;
}
document.getElementById('test').value = formattedNumber;
}
<input type="number" id="test" class="test" onkeypress="numberWithCommas(this.value)">
Some notes:
Because you want commas, the type is not a number, it's a string
Because you want to work on the input after you type, it's onkeyup not onkeypressed
I have a solution that does a regex replace for 3 characters with 3 characters PLUS a comma:
var x = "1234567";
x.replace(/.../g, function(e) { return e + ","; } );
// Gives: 123,456,7
i.e. almost the right answer, but the commas aren't in the right spot. So let's fix it up with a String.prototype.reverse() function:
String.prototype.reverse = function() {
return this.split("").reverse().join("");
}
function reformatText() {
var x = document.getElementById('test').value;
x = x.replace(/,/g, ""); // Strip out all commas
x = x.reverse();
x = x.replace(/.../g, function(e) { return e + ","; } ); // Insert new commas
x = x.reverse();
x = x.replace(/^,/, ""); // Remove leading comma
document.getElementById('test').value = x;
}
<input id="test" class="test" onkeyup="reformatText()">
function numberWithCommas(x) {
var real_num = x.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
console.log(real_num);
document.getElementById('test').value = real_num;
}
<input type="number" id="test" onkeypress="numberWithCommas(this.value)">
Check out my fiddle here http://jsfiddle.net/6cqn3uLf/
You'd need another regex to limit to numbers but this will format based on the user's locale - which may be advantageous here.
<input id="mytext" type="text">
$(function () {
$('#btnformat').on('input propertychange paste', function () {
var x = $('#btnformat').val();
$('#btnformat').val(Number(x.replace(/,/g,'')).toLocaleString());
});
});
if jquery is not overhead for your application then you can use
https://code.google.com/p/jquery-numberformatter/

Masking the values in a textbox using jQuery

I have a textbox and onkeyup event I have to mask (with asterisk (*) character) a portion of the string (which is a credit card number) when user enter the values one after the other. e.g. say the value that the user will enter is 1234 5678 1234 2367.
But the textbox will display the number as 1234 56** **** 2367
I general if the user enters XXXX XXXX XXXX XXXX, the output will be XXXX XX** **** XXXX where X represents any valid number
The program needs to be done using jQuery. I have already made the program (and it is working also) which is as follows:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script>
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
var CCNValue = $(this).val();
var CCNLength = CCNValue.length;
$.each(CCNValue, function(i) {
if (CCNLength <= 7) {
$("#txtCCN").val(CCNValue);
} //end if
if (CCNLength >= 8 && CCNLength <= 14) {
$("#txtCCN").val(CCNValue.substring(0, 7) + CCNValue.substring(7, CCNLength).replace(/[0-9]/g, "*"));
} //end if
if (CCNLength >= 15) {
$("#txtCCN").val(CCNValue.substring(0, 7) + CCNValue.substring(7, 15).replace(/[0-9]/g, "*") + CCNValue.substring(15));
} //end if
});
});
});
</script>
</head>
<body>
<input type="text" id="txtCCN" maxlength=19 />
</body>
</html>
But I think that the program can be optimized/re-written in a much more elegant way.
N.B. I don't need any validation at present.
No need of any condition of length, substring and replace can be directly used on the string of any length safely.
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
var CCNValue = $.trim($(this).val());
$(this).val(CCNValue.substring(0, 7) + CCNValue.substring(7, 15).replace(/\d/g, "*") + CCNValue.substring(15));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="text" id="txtCCN" maxlength=19 />
val can also be used
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
$(this).val(function(i, v) {
return v.substring(0, 7) + v.substring(7, 15).replace(/\d/g, "*") + v.substring(15);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="text" id="txtCCN" maxlength=19 />
The same can be done in VanillaJS
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('txtCCN').addEventListener('keyup', function() {
var value = this.value.trim();
this.value = value.substring(0, 7) + value.substring(7, 15).replace(/\d/g, '*') + value.substring(15);
}, false);
});
<input type="text" id="txtCCN" required maxlength="19" />
Try It: Its 100% workable...
$(document).ready(function () {
$("#txtCCN").keyup(function (e) {
var CCNValue = $(this).val();
CCNValue = CCNValue.replace(/ /g, '');
var CCNLength = CCNValue.length;
var m = 1;
var arr = CCNValue.split('');
var ccnnewval = "";
if (arr.length > 0) {
for (var m = 0; m < arr.length; m++) {
if (m == 4 || m == 8 || m == 12) {
ccnnewval = ccnnewval + ' ';
}
if (m >= 6 && m <= 11) {
ccnnewval = ccnnewval + arr[m].replace(/[0-9]/g, "*");
} else {
ccnnewval = ccnnewval + arr[m];
}
}
}
$("#txtCCN").val(ccnnewval);
});
});
One thing you might consider is deleting the first two if statements. All of the work your function does is contained within the last one, so you could just change it from
if(CCNLength >= 15)
to
if(CCNLength >= 8)
This seems to maintain the functionality while cutting out some repetition in your code.
Adding a generic routine for customizing space points and mask range in the input data. This will also respect the space characters as you originally asked for.
$(function () {
$("#cardnum").keyup(function (e) {
var cardNo = $(this).val();
//Add the indices where you need a space
addSpace.call(this, [4, 9, 14], cardNo );
//Enter any valid range to add mask character.
addMask.call(this, [7, 15], $(this).val()); //Pick the changed value to add mask
});
function addSpace(spacePoints, value) {
for (var i = 0; i < spacePoints.length; i++) {
var point = spacePoints[i];
if (value.length > point && value.charAt(point) !== ' ')
$(this).val((value.substr(0, point) + " "
+ value.substr(point, value.length)));
}
}
function addMask(range, value) {
$(this).val(value.substring(0, range[0])
+ value.substring(range[0], range[1]).replace(/[0-9]/g, "*")
+ value.substring(range[1]));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="cardnum" maxlength="19" />

How can I show a dollar sign before the amount value when the checkbox is checked?

When the checkbox is not checked it will show $0.00.
When I check the checkbox, it will show 1.00. I want it to show $1.00. How can I do that?
Demo on JS Fiddle
This is the code:
<form id="form1" method="post">
<input type="text" id="totalcost" value="$0.00">
<input type="checkbox" value="aa_1">
<input type="checkbox" value="aa_2">
<input type="checkbox" value="aa_3">
</form>
<script type="text/javascript">
var clickHandlers = (function () {
var form1 = document.getElementById("form1"),
totalcost = document.getElementById("totalcost"),
// if this is always the last input in the form, we could avoid hitting document again with
// totalcost = form1[form1.length - 1];
sum = 0;
form1.onclick = function (e) {
e = e || window.event;
var thisInput = e.target || e.srcElement;
if (thisInput.nodeName.toLowerCase() === 'input') {
if (thisInput.checked) {
var val = thisInput.value, // "bgh_9.99"
split_array = val.split("_"), // ["bgh", "9.99"]
pay_out_value = split_array[1]; // "9.99"
sum += parseFloat(pay_out_value); // 9.99
} else {
if (thisInput.type.toLowerCase() === 'checkbox') {
var val = thisInput.value, // "bgh_9.99"
split_array = val.split("_"), // ["bgh", "9.99"]
pay_out_value = split_array[1]; // "9.99"
sum -= parseFloat(pay_out_value); // 9.99
}
}
totalcost.value = (sum > 0) ? sum.toFixed(2) : "$0.00";
}
}
return null;
}());
</script>
Simply change this line:
totalcost.value = (sum > 0) ? sum.toFixed(2) : "$0.00";
to
totalcost.value = (sum > 0) ? "$" + sum.toFixed(2) : "$0.00";
^
This will add $ before your price !
FIDDLE
Just append the $ to the value:
totalcost.value = (sum > 0) ? '$' + sum.toFixed(2) : "$0.00";
Fiddle

Categories