I have this input tag where you put the total of your receipt :
<input type="text" name="currency" id="currency" class="text-input" onBlur="this.value=formatCurrency(this.value);" />
The Javascript is as follows:
<script type="text/javascript">
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num)) {
num = "0";
}
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num % 100;
num = Math.floor(num/100).toString();
if(cents < 10) {
cents = "0" + cents;
}
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
}
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
</script>
Users can only enter receipts more than $10.00 bucks, how can I set that on my script? Also they need to know they can not enter currency less than $10.
From what I can gather from your question I think you are looking for something like this. Basically if we have a valid entry such as $100.00 we continue, return true etc, else if we have something that looks like an int or float we can reformat this and recurse the function, else hint user for of vaild entry
var foo = document.getElementById('foo');
foo.addEventListener('blur', function(e) {
var val = e.target.value;
var err = document.getElementById('err');
var errMsg = 'please enter a value $10.00 or greater';
var patt = /^\$\d+\.\d{2}$/;
var amount = parseInt(val.replace(/\$|\./g, ''));
if (val !== '') {
if (patt.test(val)) {
if (amount < 1000) {
err.textContent = errMsg;
} else {
document.getElementById('suc')
.textContent = 'processing request';
}
} else if (typeof amount == 'number' && !/[a-z]/g.test(val)) {
if (/\.\d{2}/.test(val)) {
e.target.value = '$' + (amount / 100);
} else {
e.target.value = '$' + amount + '.00';
}
arguments.callee(e);
} else {
err.textContent = errMsg;
}
}
});
here is a demo
You can apply a validation function when submitting the form to test if the value is below a threshold, such as:
function validate()
{
value = document.getElementById('currency');
if (value <= 10.00)
{
return false
} else
{
return true;
}
}
You could also apply this to the onblur event, but my preference is to present validation errors when the form is submitted.
It looks like you're trying to parse a string, convert it nicely into dollars and cents, and reject it if it's less than 10. There's a much nicer way to do that:
function formatCurrency(num) {
// Remove the dollar sign
num = num.replace("$", "");
// Change the string to a float, and limit to 2 decimal places
num = parseFloat(num);
Math.round(num * 100) / 100;
// If its less than 10, reject it
if(num < 10) {
alert("Too small!");
return false;
}
// Return a nice string
return "$" + num;
}
At the end, are you trying to return -$99.94 if the number is negative?
Related
Probably an beginner question. When a counter I have on my page hits 10000 I am looking to reset the number to 1 and show "+10k" next to it.
For example, if the counter response was 10010 it would display as follows:
Image of UI
Is there a more efficient way of doing the following:
Set one ID to reset the number to 1 when it hits 10000
Change the display settings of another ID when API response value hits 10000
// below changes 10000 to 1
function kFormatter(num) {
if (num > 1 && num < 10000) {
return Math.abs(num) ? Math.sign(num)*((Math.abs(num)-0).toFixed(1)): Math.sign(num)*Math.abs(num)
}
else if (num > 10000 && num < 20000) {
return Math.abs(num) ? Math.sign(num)*((Math.abs(num)-500).toFixed(1)): Math.sign(num)*Math.abs(num)
}
}
// Below script shows +10k copy
function show10k(num) {
if (num > 1 && num < 10000) {
document.getElementById("10k-text").style.display = "none";
}
else if (num > 10000 && num < 20000) {
document.getElementById("10k-text").style.display = "flex";
}
}
// output
function websiteVisits(response) {
document.querySelector("#visits").textContent = (kFormatter, show10k)(response.value);
}
I'm not sure of the constraints of your project but this is how I would achieve the same thing:
if (input.value > 10000) {
let tenKays = Math.floor(input.value / 10000)
let digits = input.value % 10000
output.innerHTML = digits + " " + "+" + tenKays + "0K"
} else {
output.innerHTML = input.value
}
It could be polished in different ways to display the actual output in a more sophisticated way but it's a simple method that handles numbers of any size.
first : function kFormatter(num) of you is wrong :
(Math.abs(num)-500) should change to (Math.abs(num)-10000)
(kFormatter, show10k) is returned show10k (document):
(kFormatter, show10k)(response.value) <=> show10k(response.value)
You can call 2 function same as :
document.querySelector("#visits").textContent = kFormatter(response.value);
show10k(response.value)
or call show10k() in kFormatter() same as :
function kFormatter(num) {
if (num > 1 && num < 10000) {
show10k("none")
return Math.abs(num) ? Math.sign(num)*((Math.abs(num)-0).toFixed(1)):
Math.sign(num)*Math.abs(num)
} else if (num > 10000 && num < 20000) {
show10k("flex")
return Math.abs(num) ? Math.sign(num)*((Math.abs(num)-10000).toFixed(1)):
Math.sign(num)*Math.abs(num)
}
}
// Below script shows +10k copy
function show10k(display) {
document.getElementById("10k-text").style.display = display;
}
Example :
const valueInput = document.getElementById('number');
const formatNumber = (value) => {
return parseInt(value)
}
valueInput.addEventListener('input', function() {
valueInput.value = formatNumber(this.value);
websiteVisits(this.value)
});
const kFormatter = num => {
let visit = num%10000
let xk = parseInt(num/10000)
showxk(xk)
return visit
}
// Below script shows +10k copy
const showxk = xk => {
let xkEle = document.getElementById("xk-text");
if (!xk) {
xkEle.classList.add('hide')
} else {
xkEle.classList.remove('hide')
xkEle.textContent = (Math.sign(xk) > 0 ? '+' : '') + xk + '0k'
}
}
const websiteVisits = value => {
document.querySelector("#visits").textContent = kFormatter(value)
}
.hide {
display:none;
}
<span id="visits"></span><sup id='xk-text' class="hide"></sup>
<hr />
<input type="number" id="number" step="1">
I have a function that calculates the price something.
When the age < 5 then price = 0,
when the age < 15 the price = price/2
and when age > 15 the price = price + price*0.15. The first 2 are working fine but the last one has a problem. When for example a put 100 on the price input and 26 on the age input the answer that it gives me is 10015.
<script>
function add(x, y) {
return x+y;
}
function Subtract(x, y) {
return x-y;
}
function Divide(x, y) {
return x/y;
}
function Multiply(x, y) {
return x*y;
}
var plusPrice = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
var plusButton = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
function updateClickCount() {
document.getElementById("clicks").innerHTML = plusButton();
if (document.getElementById("price").value !== '') {
document.getElementById("input").innerHTML = plusPrice();
}
}
function checkInputs() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
if( parseInt(price) < 0 || isNaN(parseInt(price))) {
window.alert("Please insert a valid price");
price = '';
}
if(parseInt(age) > 100 || parseInt(age) < 0 || isNaN(parseInt(age))){
window.alert("Please insert a valid age");
age = '';
}
}
function Calculate() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
if (document.getElementById("price").value !== '' && document.getElementById("age").value !== '') {
if (age<5) {
document.getElementById("demo").innerHTML = Subtract(price,price);
} else if (age < 15 && age >= 5) {
document.getElementById("demo").innerHTML = Divide(price,2);
} else {
document.getElementById("demo").innerHTML = add(price,Multiply(price,0.15));
}
} else {
window.alert("Please fill both age and price to calculate the amount you have to pay");
}
}
</script>
<body>
Please enter the price: <br>
<input type="text" id="price"><button onclick="document.getElementById('price').value = ''">Clear input field</button><br><br>
Please enter your age: <br>
<input type="text" id="age"><button onclick="document.getElementById('age').value = ''">Clear input field</button><br><br>
<button onclick="checkInputs(); updateClickCount(); Calculate();">Calculate price</button>
<p id="totalPrice">The total amount you have to pay is: </p><br>
<p id="demo"></p>
<p>Button Clicks: <a id="clicks">0</a></p>
<p>Correct Price Fill Count: <span id="input">0</span></p>
</body>
Apparently, price is a string. Replace
var price = document.getElementById("price").value;
with
var price = parseFloat(document.getElementById("price").value);
The function has already worked for subtraction and division, because operators - and / can't be applied to strings, so JS coerces them to numbers. The +, however, has a string-compatible interpretation (string concatenation), so type coercion doesn't happen.
or do this
var price = Number(document.getElementById("price").value);
In JavaScript the + symbol can be used both for numeric addition and string concatenation, depending on the variables either side. For example,
console.log('value:' + 4); // 'value:4'
console.log(3 + 1); // 4
console.log('value:' + 4 + '+' + 1); // 'value:4+1'
console.log('value:' + 4 + 1); // 'value:41'
console.log('value:' + (3 + 1)); // 'value:4'
console.log(4 + ' is the value'); // '4 is the value
Hence convert your operands to numeric type before proceeding with addition so that they are not concatenated.
Hope this clarifies.
I am trying to validate user input in a text input field.
I have written a javascript function for the same purpose which fires on onkeyup event.
The goal is to only allow user input if it's a numeric value less than 100 and with at most 1 decimal place.
The function is working fine but if a enter an invalid character ,say 'a', it will flash in the input box before being removed.
What I want is that if the entered character violates the defined condition it should not appear in the input box (as it is flashing right now for a split second).
Here's my code:
function validatePercent(event) {
var txt = $("#tds_input").val();
// alert(event.source);
if (!parseInt(txt)) {
$("#tds_input").val('');
}
if (isNaN(txt / 1)) {
txt = txt.substr(0, txt.length - 1);
$("#tds_input").val(txt);
}
if (txt > 100) {
//alert(2);
txt = txt.toString();
txt = txt.substr(0, txt.length - 1);
$("#tds_input").val(txt);
}
txt = txt.toString();
if (txt.indexOf('.') > -1) {
if (txt.substr(txt.indexOf('.') + 1, txt.length).length > 1) {
txt = txt.substr(0, txt.length - 1);
$("#tds_input").val(txt);
}
}
}
Using type=number (and not text) can help
function validatePercent(event)
{
var txt=$("#tds_input").val();
if(!parseInt(txt))
{
$("#tds_input").val('');
}
if(isNaN(txt/1))
{
txt=txt.substr(0,txt.length-1);
$("#tds_input").val(txt);
}
if(txt>100)
{
txt=txt.toString();
txt=txt.substr(0,txt.length-1);
$("#tds_input").val(txt);
}
txt=txt.toString();
if(txt.indexOf('.')>-1)
{
if(txt.substr(txt.indexOf('.')+1,txt.length).length>1){
txt=txt.substr(0,txt.length-1);
$("#tds_input").val(txt);
}
}
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id = "tds_input" onkeyup="validatePercent()">
UPDATED
You could store the value of the when the focus is in the input.
When the user enters a valid percentage (integer only), replace the value stored. When inputs is incorrect, just replace with the old value.
var decimalSeparator = 1.1.toLocaleString().replace(/\d/g, ''),
pattern1 = "^(\\d{1,3})?([",
pattern2 = "]?\\d{1})?$",
regex = new RegExp(pattern1+decimalSeparator+pattern2),
resetContent = function () {
$('#tds_input').val($('#tds_input').data('val'));
},
matchRegex = function (value) {
return value.match(regex);
};
$('#tds_input').bind('focusin', (e) => {
$('#tds_input').data('val', $('#tds_input').val());
});
// handle input (keys, paste)
$('#tds_input').bind('input', (e) => {
let txtValue = $('#tds_input').val();
// input is empty
if (txtValue === "") {
$('#tds_input').data('val', "");
return;
}
// value does not match regex
if (!matchRegex(txtValue)) {
// maybe it ends with the decimal character?
if (txtValue[txtValue.length - 1] === "." && txtValue !== "100.") {
// simulate the user enters a decimal next
if (matchRegex(txtValue + "1")) {
$('#tds_input').data('val', txtValue);
return;
}
}
resetContent();
return;
}
// check between 0 and 100
let value = parseFloat(txtValue);
if (value >= 0 && value <= 100) {
// store new valid number
$('#tds_input').data('val', value);
// put the value as an integer in the input
$('#tds_input').val(value);
return;
} else resetContent();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tds_input"/>
I'm trying to make a program that generates a random number which the user guesses. It also limits the number of guesses the user can make (or is supposed to.)
var highLimit = 5;
var randNum = Math.floor((Math.random() * highLimit) + 1);
var allowedGuesses = 2;
var numGuesses = 0;
function guessingGame() {
if (numGuesses <= allowedGuesses) {
do {
inputNum = document.numForm.number.value;
inputNum = parseInt(inputNum);
if (inputNum < randNum && inputNum > 1) {
document.numForm.gameResults.value = "Sorry, your guess was too low.";
numGuesses++;
}
else if (inputNum > randNum && inputNum < highLimit) {
document.numForm.gameResults.value = "Sorry, your guess was too high.";
numGuesses++;
}
else if (inputNum == randNum) {
document.numForm.gameResults.value = "Congratulations! You guessed correctly.";
numGuesses++;
}
else {
document.numForm.gameResults.value = "Your guess was out of the desired parameters. Please guess again.";
numGuesses--;
}
} while(numGuesses < allowedGuesses && inputNum != randNum);
}
else {
document.numForm.gameResults.value = "Sorry, you have reached the allowed number of guesses, which is " + allowedGuesses + "." + " Click 'New Game' to try again.";
}
return false;
}
numGuesses = 0;
function newGame() {
randNum = Math.floor((Math.random() * highLimit) + 1);
guessingGame();
return false;
}
And the HTML:
<form name = "numForm">
<fieldset>
<label for = "randNum">Enter a number between 1 and 5: </label>
<input type = "text" name = "number" value = "" id = "randNum" size = "1" maxlength = "1" />
</fieldset>
<input class = "button" type = "button" name = "submit" onclick = "guessingGame()" value = "Submit Number" />
<input class = "button" type = "reset" name = "newGame" onclick = "newGame()" value = "New Game" />
<fieldset>
<textarea name = "gameResults" onclick = "" readonly = "true" value = "" rows = "5" cols = "40" ></textarea>
</fieldset>
</form>
Right now, the program is stuck in a infinite loop since highLimit is set at 5. But if I set it at ten, the program works. How can I fix it so it works at any value? I would also appreciate other suggestions for improvement.
Thanks in advance!
I think you don't need a loop in this one. You can simple say:
function guessingGame() {
if (numGuesses < 0){numGuesses=0;}
if ((numGuesses < allowedGuesses) && (inputNum != randNum)) {
inputNum = document.numForm.number.value;
inputNum = parseInt(inputNum);
if (inputNum < randNum && inputNum > 1) {
document.numForm.gameResults.value = "Sorry, your guess was too low.";
numGuesses++;
}
else if (inputNum > randNum && inputNum < highLimit) {
document.numForm.gameResults.value = "Sorry, your guess was too high.";
numGuesses++;
}
else if (inputNum == randNum) {
document.numForm.gameResults.value = "Congratulations! You guessed correctly.";
numGuesses++;
}
else {
document.numForm.gameResults.value = "Your guess was out of the desired parameters. Please guess again.";
numGuesses--;
}
}
else {
document.numForm.gameResults.value = "Sorry, you have reached the allowed number of guesses, which is " + allowedGuesses + "." + " Click 'New Game' to try again.";
}
return false;
}
the if (numGuesses < 0){numGuesses=0;} will help also. for negative cases.
This is an update for:
Ran the Snippet and answeared in "0 tries"
This is how I did it: But you're going to have to replace the 'prompts' and 'alerts' with your specified inputs and outputs, if you still need it after 4 years:
let maximum = parseInt(prompt('Enter the maximum number!') );
while(!maximum) {
maximum = parseInt (prompt('Please enter a valid number') )
}
const targetNum = Math.floor(Math.random()*maximum)+1;
let attempts =0;
let maxAttempts = Math.ceil(maximum/2);
// ==== Uncomment the line below to cheat --> ======
// console.log(targetNum)
let guess = parseInt(prompt(`Enter your first guess!, you have ${maxAttempts} attempts (press 'q' anytime to escape from this hellish nightmare)`));
while(parseInt(guess) !==targetNum && attempts < maxAttempts-1) {
if (typeof(guess) === 'string' && guess.toLowerCase() ==='q') {break;}
attempts++;
if(guess>targetNum) {
guess = (prompt(`Too High! Enter new guess! attempts left: ${maxAttempts- attempts} (press 'q' anytime to escape from this hellish nightmare)`))
}else {
guess= (prompt(`Too low! Entere a new Guess! attempts left: ${maxAttempts- attempts} (press 'q' anytime to escape from this hellish nightmare)`))
}
}
if(typeof(guess) === 'string' && guess.toLowerCase() ==='q') {
alert(`You gave up after ${attempts} attempts`);
}
else if(attempts >= maxAttempts-1) {alert(`Oops, your ${maxAttempts} attempts ran out, the number was ${targetNum}: Verification : ${targetNum==guess}`);}
else {
alert(`Good job, you got it ${attempts+1} attempts!, the number was ${targetNum}: Verification : ${targetNum==guess}`) ;
}
Here's my attempt at limiting the number of characters entered into a text area:
var limit = 255;
var txt = $('textarea[id$=txtPurpose]');
$(txt).keyup(function() {
var len = $(this).val().length;
if (len > limit) {
//this.value = this.value.substring(0, 50);
$(this).addClass('goRed');
$('#spn').text(len - limit + " characters exceeded");
return false;
} else {
$(this).removeClass('goRed');
$('#spn').text(limit - len + " characters left");
}
});
However, it doesn't work very well. How can I prevent a user from entering text once a certain limit has been reached, say 255 characters?
Though this question is pretty old. If I was you I do something very simple like
<textarea maxlength="255"></textarea>
This would limit the users to enter only 255 characters in the textarea.
Here's what I use to limit something to 1200 chars. When someone types too many characters, I just truncate the contents of that textarea.
$(function() {
//set up text length counter
$('#id_limited_textarea').keyup(function() {
update_chars_left(1200, $('#id_limited_textarea')[0], $('#text_chars_left'));
});
//and fire it on doc ready, too
update_chars_left(1200, $('#id_limited_textarea')[0], $('#text_chars_left'));
});
function update_chars_left(max_len, target_input, display_element) {
var text_len = target_input.value.length;
if (text_len >= max_len) {
target_input.value = target_input.value.substring(0, max_len); // truncate
display_element.html("0");
} else {
display_element.html(max_len - text_len);
}
}
$(this).val( $(this).val().substring(0, limit) );
To simplify this to the bare bone basic:
<textarea name="message" onkeydown="return this.value.substr(0,160)"></textarea>
Set your max to where 160 is.
My plugin:
(function($) {
$.fn.textCounter = function(options) {
var defaults = {
maxlimit: 100, // max limit character
description: null, // element for descript count character
enter: true // if accept enter
};
var options = $.extend({}, defaults, options);
if (options.description != null) {
if (typeof options.description == 'string')
options.description = $('#' + options.description);
}
var fevent = function(ev) {
var value = $(this).val(),
k = ev.charCode || ev.keyCode || ev.which,
incremente = 1;
if (k == 8)
incremente = -1;
if (options.enter == false && k == 13)
return false;
if (ev.ctrlKey || ev.altKey || ev.metaKey) //Ignore
return true;
if ((value.length + incremente) > options.maxlimit)
return false;
return true;
};
var fcounter = function(ev) {
var value = $(this).val();
$(options.description).text(options.maxlimit - value.length);
};
$(this).each(function(i, el) {
if ($(this).is(':input')) {
$(this).unbind('keypress.textCounter').bind('keypress.textCounter', fevent);
$(this).unbind('keyup.textCounter').bind('keyup.textCounter', fcounter);
}
});
};
})(jQuery);
var limit="NO of characters";<br><br>
$(this).val( $(this).val().substring(0, limit) );