A input-field could have values like:
23
23-45
No I want to correct the value:
string.replace(/[^\d-]/g,'');
But that doesn't correct these values:
-45
23-
45-23
10-110
All these values are incorrect (The valid values are from 0-100 (as they are percentage values), so 110 is unvalid). So for that cases I want the user to have a second look at the input field...
I guess I have to create a second RegEx for these unvalid cases, right?
function to return true if a percentage is represented by whole numbers, where if a dash is included the first number is less than the second, and both numbers are between 0 and 100:
function isValidPercentage(input) {
var mat = /^(\d+)(?:-(\d+))?$/.exec(input + "");
if (mat !== null && ((mat[2] === undefined && mat[1] < 101) || (mat[1] < mat[2] && mat[2] < 101))) {
return true;
}
return false;
}
Edit#1: To force the false return if either number is greater than 100
Edit#2: Fixed errors, cleaned up the code a bit
Say you have an input (#perc) and a button (#calc), then try:
document.querySelector('#calc').addEventListener('click', calculate);
function calculate() {
// replace all non numeric values in the input with nothing
// and convert it to a Number (using the + operator).
var value = +(document.querySelector('#perc').value.replace(/[^\d]/g, ''));
// now you can check the value
alert( !isNaN(value) && value >= 0 && value <= 100
? 'ok ' + value
: 'not ok ' + value );
}
The SO-inline code inserter is not working, so you'll have to try it out yourself.
Related
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
I need javascript to add 5 to an integer variable, but instead it treats the variable as a string, so it write out the variable, then add 5 onto the end of the "string". How can I force it to do math instead?
var dots = document.getElementById("txt").value; // 5
function increase(){
dots = dots + 5;
}
Output: 55
How can I force it to output 10?
You have the line
dots = document.getElementById("txt").value;
in your file, this will set dots to be a string because the contents of txt is not restricted to a number.
to convert it to an int change the line to:
dots = parseInt(document.getElementById("txt").value, 10);
Note: The 10 here specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.
the simplest:
dots = dots*1+5;
the dots will be converted to number.
DON'T FORGET - Use parseFloat(); if your dealing with decimals.
I'm adding this answer because I don't see it here.
One way is to put a '+' character in front of the value
example:
var x = +'11.5' + +'3.5'
x === 15
I have found this to be the simplest way
In this case, the line:
dots = document.getElementById("txt").value;
could be changed to
dots = +(document.getElementById("txt").value);
to force it to a number
NOTE:
+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5
parseInt() should do the trick
var number = "25";
var sum = parseInt(number, 10) + 10;
var pin = number + 10;
Gives you
sum == 35
pin == "2510"
http://www.w3schools.com/jsref/jsref_parseint.asp
Note: The 10 in parseInt(number, 10) specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.
This also works for you:
dots -= -5;
You can add + behind the variable and it will force it to be an integer
var dots = 5
function increase(){
dots = +dots + 5;
}
Number()
dots = document.getElementById("txt").value;
dots = Number(dots) + 5;
// from MDN
Number('123') // 123
Number('123') === 123 /// true
Number('12.3') // 12.3
Number('12.00') // 12
Number('123e-1') // 12.3
Number('') // 0
Number(null) // 0
Number('0x11') // 17
Number('0b11') // 3
Number('0o11') // 9
Number('foo') // NaN
Number('100a') // NaN
Number('-Infinity') //-Infinity
its really simple just
var total = (1 * yourFirstVariablehere) + (1 * yourSecondVariablehere)
this forces javascript to multiply because there is no confusion for * sign in javascript.
After trying most of the answers here without success for my particular case, I came up with this:
dots = -(-dots - 5);
The + signs are what confuse js, and this eliminates them entirely. Simple to implement, if potentially confusing to understand.
UPDATED since this was last downvoted....
I only saw the portion
var dots = 5
function increase(){
dots = dots+5;
}
before, but it was later shown to me that the txt box feeds the variable dots. Because of this, you will need to be sure to "cleanse" the input, to be sure it only has integers, and not malicious code.
One easy way to do this is to parse the textbox with an onkeyup() event to ensure it has numeric characters:
<input size="40" id="txt" value="Write a character here!" onkeyup="GetChar (event);"/>
where the event would give an error and clear the last character if the value is not a number:
<script type="text/javascript">
function GetChar (event){
var keyCode = ('which' in event) ? event.which : event.keyCode;
var yourChar = String.fromCharCode();
if (yourChar != "0" &&
yourChar != "1" &&
yourChar != "2" &&
yourChar != "3" &&
yourChar != "4" &&
yourChar != "5" &&
yourChar != "6" &&
yourChar != "7" &&
yourChar != "8" &&
yourChar != "9")
{
alert ('The character was not a number');
var source = event.target || event.srcElement;
source.value = source.value.substring(0,source.value-2);
}
}
</script>
Obviously you could do that with regex, too, but I took the lazy way out.
Since then you would know that only numbers could be in the box, you should be able to just use eval():
dots = eval(dots) + 5;
I'm using the typeof command to make sure that only 1 of the 2 input fields of this temperature (Celsius to/from Fahrenheit) calculator is populated with data and it has to be a number. If the input is not a valid number or both fields are populated, the app will throw an error message.
The problem: nothing satisfies this condition - the errorMessage is always shown, even if I type in a valid number.
Is typeof the right solution to this problem? If it is, why is this code not working?
document.getElementById('temperature-form').addEventListener('submit', calculateResult);
function calculateResult(e) {
e.preventDefault();
const celsiusInput = document.getElementById('celsius');
const fahrenheitInput = document.getElementById('fahrenheit');
let resultOutput = document.getElementById('result');
// validate input data type and calculate result
if ((typeof celsiusInput === 'number') && (fahrenheitInput === null)) {
resultOutput.value = (celsiusInput.value * 1.8 + 32) + ' Fahrenheit';
} else if ((celsiusInput === null) && (typeof fahrenheitInput === 'number')) {
resultOutput.value = ((fahrenheitInput.value - 32)/1.8) + ' Celsius';
} else {
errorMessage('Please add a number in one of these fields');
}
}
Many thanks!
You could check the value properties of each input to see if they are numbers using the isNaN() function like so:
function calculateResult(e) {
e.preventDefault();
//Get the value of each input box
const celsiusValue = document.getElementById('celsius').value;
const fahrenheitValue = document.getElementById('fahrenheit').value;
//Get the result element
let resultOutput = document.getElementById('result');
// validate input data type and calculate result
if(!isNaN(celsiusValue) && (fahrenheitValue === null || fahrenheitValue === "")){
//Only celsiusValue has a valid number
resultOutput.value = (celsiusValue * 1.8 + 32) + ' Fahrenheit';
}else if(!isNaN(fahrenheitValue ) && (celsiusValue === null || celsiusValue === "")){
//Only fahrenheitValue has a valid number
resultOutput.value = ((fahrenheitValue - 32)/1.8) + ' Celsius';
}else if(!isNan(celsiusValue) && !isNan(fahrenheitValue )){
//Both contain a valid number
//Figure this one out as you didn't account for it
}else{
//Neither is a valid number
errorMessage('Please add a number in one of these fields');
}
}
Documentation of isNaN():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
When doing const celsiusInput = document.getElementById('celsius') you're getting the DOM Element, not the value.
In order to obtain de value you'd have to check for the property value.
So you'd end up with something like this:
const celsiusInput = document.getElementById("celsius")
const celsiusValue = celsiusInput.value
Now if we do typeof celsiusValue we'll always get string, because text/number inputs always accept text (check input's type property for more info).
The proper way to check if there are numbers or letters is using Regular Expressions.
I'll leave a simple example to act as a starting point for you:
const celsiusInput = document.getElementById("celsius")
const celsiusValue = celsiusInput.value
if(/\D/.test(celsiusValue)) {
alert("There is something that's not a number in the Celsius input!")
}
First of by doing a comparison like this fahrenheitInput === null you're comparing a DOM element against the value null.
That will only evaluate to true if the DOM Element never existed.
Secondly the typeof method will always evaluate to a String on DOM element types, so again this will always be false.
To really get what you want you have to do a proper check
To check if both input fields are supplied, simply checking the length of the values will surface:
if(fahrenheitInput.length > 0 && celsiusInput.length > 0) //fail
If fahrenheitInput only is given:
if(!isNaN(Number(fahrenheitInput)) //convert
if celsiusInput only is given:
if(!isNaN(Number(celsiusInput)) //convert
Finally if all checks above don't check our, fail
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
I need javascript to add 5 to an integer variable, but instead it treats the variable as a string, so it write out the variable, then add 5 onto the end of the "string". How can I force it to do math instead?
var dots = document.getElementById("txt").value; // 5
function increase(){
dots = dots + 5;
}
Output: 55
How can I force it to output 10?
You have the line
dots = document.getElementById("txt").value;
in your file, this will set dots to be a string because the contents of txt is not restricted to a number.
to convert it to an int change the line to:
dots = parseInt(document.getElementById("txt").value, 10);
Note: The 10 here specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.
the simplest:
dots = dots*1+5;
the dots will be converted to number.
DON'T FORGET - Use parseFloat(); if your dealing with decimals.
I'm adding this answer because I don't see it here.
One way is to put a '+' character in front of the value
example:
var x = +'11.5' + +'3.5'
x === 15
I have found this to be the simplest way
In this case, the line:
dots = document.getElementById("txt").value;
could be changed to
dots = +(document.getElementById("txt").value);
to force it to a number
NOTE:
+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5
parseInt() should do the trick
var number = "25";
var sum = parseInt(number, 10) + 10;
var pin = number + 10;
Gives you
sum == 35
pin == "2510"
http://www.w3schools.com/jsref/jsref_parseint.asp
Note: The 10 in parseInt(number, 10) specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.
This also works for you:
dots -= -5;
You can add + behind the variable and it will force it to be an integer
var dots = 5
function increase(){
dots = +dots + 5;
}
Number()
dots = document.getElementById("txt").value;
dots = Number(dots) + 5;
// from MDN
Number('123') // 123
Number('123') === 123 /// true
Number('12.3') // 12.3
Number('12.00') // 12
Number('123e-1') // 12.3
Number('') // 0
Number(null) // 0
Number('0x11') // 17
Number('0b11') // 3
Number('0o11') // 9
Number('foo') // NaN
Number('100a') // NaN
Number('-Infinity') //-Infinity
its really simple just
var total = (1 * yourFirstVariablehere) + (1 * yourSecondVariablehere)
this forces javascript to multiply because there is no confusion for * sign in javascript.
After trying most of the answers here without success for my particular case, I came up with this:
dots = -(-dots - 5);
The + signs are what confuse js, and this eliminates them entirely. Simple to implement, if potentially confusing to understand.
UPDATED since this was last downvoted....
I only saw the portion
var dots = 5
function increase(){
dots = dots+5;
}
before, but it was later shown to me that the txt box feeds the variable dots. Because of this, you will need to be sure to "cleanse" the input, to be sure it only has integers, and not malicious code.
One easy way to do this is to parse the textbox with an onkeyup() event to ensure it has numeric characters:
<input size="40" id="txt" value="Write a character here!" onkeyup="GetChar (event);"/>
where the event would give an error and clear the last character if the value is not a number:
<script type="text/javascript">
function GetChar (event){
var keyCode = ('which' in event) ? event.which : event.keyCode;
var yourChar = String.fromCharCode();
if (yourChar != "0" &&
yourChar != "1" &&
yourChar != "2" &&
yourChar != "3" &&
yourChar != "4" &&
yourChar != "5" &&
yourChar != "6" &&
yourChar != "7" &&
yourChar != "8" &&
yourChar != "9")
{
alert ('The character was not a number');
var source = event.target || event.srcElement;
source.value = source.value.substring(0,source.value-2);
}
}
</script>
Obviously you could do that with regex, too, but I took the lazy way out.
Since then you would know that only numbers could be in the box, you should be able to just use eval():
dots = eval(dots) + 5;
In my React project I am currently filtering data by price, using the min and max. In my max price conditional I check if the max price is empty or if not I check to see if the price for the current data can pass the filter
( !this.state.max_price.trim() || listing.price <= this.state.max_price )
I noticed that it will work when entering a max price for every number that doesn't exceed 1000, but as soon as a number 1000 or higher was entered it failed, and return false so I tested out the conditional in jsfiddle to see if I was missing something. Below I got an unexpected result
// I put this in jsfiddle, and it returned false
if ("300" <= "1000") {
alert('true')
} else {
alert('false')
}
I also put this code below in jsfiddle and was met with a result I expected (as you can see it is working for numbers below 1000 but not 1000 and above)
// I put this in jsfiddle, and it returned false
if ("300" <= "500") {
alert('true')
} else {
alert('false')
}
you are comparing strings, and "300" is lexographically greater than "1000"
console.log("300" < "1000");
console.log(300 < 1000);
In string comparison in JavaScript (mostly any language), strings are compared by their ASCII values, and since the ASCII value for "3" (51) is greater than that of "1" (49) 51>49 hence "300">"1000".
You can convert the string variables to numbers using the unary + oprator +"1" => 1:
var a = "300";
var b = "1000";
if (a <= b) {
console.log('true')
} else {
console.log('false')
}
a = +a; // convert to number using the unary '+' operator
b = +b;
if (a <= b) {
console.log('true')
} else {
console.log('false')
}
I'm working on jquery.
i want to check the validation on todate and from date.
want to convert my string into double digit (need to add 0 if user enter single digit value)
how can i give double digit as user enter single digit value into textbox?
expected output is
var HourPerWeek = $("#Hour").val();
-- if user enter value 2 i need to convert it into 02
var MinPerWeek = $("#Min").val();
-- if user enter value 1 i need to convert it into 01
Instead of length of string ?
function returnDoubleDigits(str) {
return str.length === 1 ? '0' + str : str;
}
e.g.
var HourPerWeek = returnDoubleDigits($("#Hour").val());
Fiddle
Would this work,just check the string length and then add a zero if it is shorter than 2
var HourPerWeek;
if ($("#Hour").val().length < 2){
HourPerWeek = "0"+ $("#Hour").val();
}
else{
HourPerWeek = $("#Hour").val();
}
You will have to add the 0 to the beginning of the string manually like in this example:
String.prototype.paddingLeft = function (paddingValue) {
return String(paddingValue + this).slice(-paddingValue.length);
};
var HourPerWeek = $("#Hour").val().paddingLeft('00');
Explanation: You can call paddingLeft on any string. It will add the chars, that you pass as an argument to the left of the string and return a string with exactly the length of the given argument. More examples:
''.paddingLeft('00') // returns '00'
'1'.paddingLeft('00') // returns '01'
'11'.paddingLeft('00') // returns '11'
'111'.paddingLeft('00') // returns '11'
'1'.paddingLeft(' ') // returns ' 1'
Have this as a function which checks for length of passed parameter.
function returnTwoDigit(var Data){
if (Data.length != 2) {
if (Data.length == 1) {
Data= "0" + Data;
}
return Data
}