Number.IsNaN and not categorizing variable*number properly? - javascript

So I am trying to make the script recognize bad input and give no output
If I put any number each time I input something it runs the function Myfunction.
The function returns output in textarea id=t as the number inputted followed by the same number * 100 and *1000. When the input area id=1 is blank it triggers if statement as true because it checks isNaN which a blank area is, the value of id=t is then changed to blank, when I add just a letter or multiple letters to textarea id=1 it shows no input as it should. However if I input a number followed by any combination of letters in textarea id=1 it first updates output to match the number, then when the letters are typed the output doesn't change and is equal to that of inputting just the number before the letters, isNan doesn't register it as 1 and typeof doesn't register it as not a number type.
Why does this break, How do I fix this?
<!-- Unit converter iteration 2 -->
<head>
</head>
<body>
<!-- Input uses oninput event to execute function-->
<textarea type="number" oninput="return myFunction()" id="1" name="1" value="" rows="1" cols="30"></textarea><br>
<textarea readonly id="t" rows="5" cols="30"></textarea>
<script type= "application/javascript">
/*Instead of throwing alert if N is NaN, it doesn't show any output instead */
function myFunction(){
var N = parseInt(document.getElementById("1").value);
if (Number.isNaN(N) || typeof(N) != "number" ){
document.getElementById("t").value = "";}
else {
/* Outputs same variables as in iteration 1 but now the html form is textarea*/
var m = N;
var cm = m * 100;
var mm = m * 1000;
document.getElementById("t").value = ""+m+" "+cm+" "+mm;}
}
</script>
</body>
</html>

That's just because of how parseInt works. Let's focus on this part of your code:
var N = parseInt(document.getElementById("1").value);
if (Number.isNaN(N) || typeof(N) != "number" ){
document.getElementById("t").value = "";}
When parseInt is called on a string that starts with a number followed by characters (e.g. 123abc), the function will return the numbers as an integer (123 in the previous example).
Example:
num = parseInt('123abc');
console.log(num);

Related

Outputs not showing in simple odd/even code

I've just started beginning to code in JavaScript (my first attempt at any so please be patient!), so have just set myself a simple project just to create a input box, and was hoping upon clicking the calculate button to generate a "Even" or "Odd" output that shows up below the box. But somehow I can't get anything to show up. Any ideas what I'm doing wrong?
function myFunction() {
// define var num
var num = document.getElementById("number").value;
//use of if function as number is odd or even (modulo = 0 or 1)
if (num % 2 === 0) {
document.writeIn("Even");
} else {
document.writeIn("Odd");
}
}
<table id="number">
Number: <input type="number" name="name">
<input type="button" onclick="myFunction()" value="Calculate"></table>
You need to take an input with type 'text' and an id of 'number'.
Then get this value of the input and assign to another element the result, because document.writeln does not work after the page is rendered by the user agent.
function myFunction() {
var num = document.getElementById("number").value;
document.getElementById("type").innerHTML = num % 2 ? "Odd": "Even";
}
Number: <input type="text" id="number">
<input type="button" onclick="myFunction()" value="Calculate">
<div id="type"></div>

Javascript if function not working properly with getElemenById

okey so I got this, kinda look at it like u have a website were u can redeem points, now when I click redeem I dont want that the number given is lesser than 4 points and that the number given is greater than your balance of points.
Now when I click the button when the input is 2, I will get 2 alerts (alerts are for testing)
But, as soon as I click the button when I put an number lesser than my balance, I also get 2 alerts, saying number = (for example) 7 and balancehidden = 100. So I dont understand why I get those alerts. because its lesser than the balance and greater than 4.
also this is the field the balance get stored when refreshBalance() get called:
<input type=hidden id="balancehidden" name="balancehide"
value=""/>
Javascript :
<input type="text" id="number"><br>
<button type="button" class="btn btn-success" id="redeem">Redeem</button>
<body onload="refreshBalance()">
<script type="text/javascript">
document.getElementById('redeem').onclick = function() {
if(document.getElementById('number').value < 4 || document.getElementById('number').value > document.getElementById("balancehidden").value)
{
alert(document.getElementById("number").value);
alert(document.getElementById("balancehidden").value);
}
}
</script>
You're trying to see whether one string is greater than another string, but what you really want to do is compare numbers.
Counterintuitively, "4" > "100" === true while 4 > 100 === false.
Convert your values to numbers:
if(parseInt(document.getElementById('number').value) < 4 || parseInt(document.getElementById('number').value) > parseInt(document.getElementById("balancehidden").value))
Use parseFloat instead of parseInt if you expect decimals, and be aware of the radix parameter.
The problem is that you are trying to compare string values instead of integers.
Please check this jsfiddle with working code: https://jsfiddle.net/2kbcuhg9/
document.getElementById('redeem').onclick = function() {
var number = parseInt(document.getElementById('number').value);
var balance = parseInt(document.getElementById('balancehidden').value);
if(number < 4 || number > balance) {
alert(document.getElementById("number").value);
alert(document.getElementById("balancehidden").value);
}
}

Convert int with starting zeros to string to check length

I have an html input type="number" field in an html page. like this:
<input type="number">
To validate the form I need to check that the length of this field is exactly 3. To do this I convert the number to String and execute the length() function.
The problem comes when the number starts with a zero. like 065
In that case the toString() method outputs a 65 with a length of 2
Do you have any idea on how to get the correct length of the number ?
I think that you would have to have your input type as text and then use JavaScript to get the length for validation. After that you could convert it to a number using the Number() function.
Change the input type to text and restrict the input with a pattern and maxlength:
<input type="text" pattern="\d*" maxlength="3">
You can solve this one of two ways:
When the user moves focus away from the field, remove the leading zeroes
In the validation, remove the leading zeroes then check the length
There is no need to convert to a number.
Removing leading zeroes when focus is lost:
function truncateNumericInput(event) {
event = event || window.event;
event.target = event.target || event.srcElement;
if (event.target.nodeName != "INPUT" || event.target.type != "number") {
return;
}
var input = event.target,
value = event.target.value;
input.value = value.indexOf(".") > -1
? value.replace(/^0{2,}/, "0")
: value.replace(/^0+/, "");
}
if (document.addEventListener) {
document.addEventListener("blur", truncateNumericInput, true);
} else {
document.attachEvent("focusout", truncateNumericInput);
}
JSFiddle: http://jsfiddle.net/67jyg1d9/
Removing leading zeroes during validation
var regex = /^0+/;
var value = input.value.replace(regex, "");
console.log(value.length <= 3)
<input type="number" name="quantity" min="0" max="999">
this takes care that only number can be entered and only till 999 that's 3 digits at max
You can solve your problem by using input type as number. You can build your logic by using overflow and underflow as shown below.
<input id="numtest" type="number" min="10" max="20" />
document.getElementById('numtest').validity.rangeOverflow
document.getElementById('numtest').validity.rangeUnderflow
or
document.getElementById('numtest').checkValidity();
rangeUnderflow: return true if value is less then min
rangeOverflow: return true if value is greater than max value.

javascript calculation field comparison algorithm

Good day,
I have 3 text fields for input.
TotalWeight
CustomUnitWeight
CustomsNumberOfUnit
There should be a validation to make sure TotalCustomWeight matches TotalWeight (neither higher nor lower).
I started playing around trying to construct a function for validating this no luck and looking for assistance
Scenario :
User input total weight of pkg at 30, then put number of custom unit at 2 and the weight at 10. On click the function calculate 2 * 10 = 20 and look at the total weight 30 and compare the total custom weight. In this case 20 does not equal to 30 therfore throw error message.
HTML
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnitsUSA" id="CustomsNumberOfUnits" />
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onChange="ChkWeight();" />
JAVASCRIPT
$(function(ChkWeight){
$('#CustomsUnitWeight').click(function() {
var TotalWeight = document.getElementById('TotalWeight');
var CustomUnitWeight = document.getElementById('CustomsUnitWeight');
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits');
var TotalCustomWeight = CustomUnitWeight * CustomsNumberOfUnit;
if (TotalWeight != TotalCustomWeight) {
error message "pkg weight does not match total custom weight"
}
});
});
Well everything else is fine in your code just needs to put .value to get value from your input fields and converting string (simple text) to Float type and then calculate and show alert like
<body>
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnits" id="CustomsNumberOfUnits"/>
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onblur="CheckWeight()" />
//I have changed the event as onblur and calling CheckWeight() function defined in javascript below.
</body>
<script type="text/javascrit">
function CheckWeight()
{
var TotalWeight = document.getElementById('TotalWeight').value;
var CustomUnitWeight = document.getElementById('CustomsUnitWeight').value;
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits').value;
//parsing text value to Float type for multipication
var TotalCustomWeight = parseFloat(CustomUnitWeight) * parseFloat(CustomsNumberOfUnit);
if (TotalWeight != TotalCustomWeight)
{
alert("pkg weight does not match total custom weight");
}
}
</script
and Off course you must need to validate for value to be number before calculation. This works perfect.

Javascript calculation letters and numbers

<SCRIPT Language = JavaScript>
function calculate() {
a = 12
b = eval(document.form.number.value)
c = 5J7S
d = (a + b + c)
alert(d)
}
</SCRIPT>
<FORM NAME = form>
Phone: <INPUT TYPE = text SIZE = 3 value ="">
-
<INPUT TYPE = text name = number SIZE = 3 value ="">
-
<INPUT TYPE = text SIZE = 4 value ="">
<P>
<Input Type = Button NAME = b1 VALUE = "Grab Code" onClick = calculate()
</FORM>
5JG7S (Fixed Value)
5+7=12 (Added both numbers from Fixed Value)
Phone number 123-456-7890
4+5+6=15 (Prefix added together)
12+15=27 (Added numbers from the Fixed Value and the numbers that were added from the prefix)
27+5JG7S=275JG7S (Those numbers were added to the beginning of the orginal Fixed Value)
Now this Script that I have:
a is the added numbers from the Fixed Value
b is the input from the form(phone number)
c is the Fixed Value
d is adding each one up so they will display the code as an alert.
Now, if I take out c and just add a and b it performs the addition, if c is in there, it stops the process and produces nothing.
My question is, how do we add the calculated number and append it to the beginning of the fixed value?
Also, the addition works, but not the way I want it to, I want to add the 3 numbers together, the javascript adds 456+12= 468
I know this is very simple code, I am not familiar with Javascript programming and I pretty much pieced together what I found from searching.
I hope this makes sense, if this is not possible I understand.
Thanks!
using parseInt on the values should help with the math. your results are currently inaccurate because the form values are strings: rather than adding numbers you are concatenating strings.
i changed your 'number' input to have an ID attribute, so that you can select with getElementById and replaced the eval call with a call to parseInt.
the value of c in the calculate function needs to be corrected though, not sure what you meant but that will generate an error.
other various HTML tidyness issues (nothing that would break, just easier to read IMHO).
<script type="text/javascript">
function calculate() {
var a = 12;
var b = parseInt(document.getElementById("number").value);
// var c = 5J7S;
var d = (a + b + c);
alert(d);
}
</script>
<form name="form">
Phone: <input type="text" size="3" value=""/>
-
<input type="text" name="number" id="number" size="3" value=""/>
-
<input type="text" size="4" value=""/>
<p>
<input type="button" name="b1" value="Grab Code" onclick="calculate()">
</p>
</form>
hope that helps! cheers.

Categories