How can i avoid NaN error at simple form? - javascript

I've got simple form that has to return square root of a number. But i get NaN error. As you can see, variable "number" is number-type. What am i doing wrong?
let number = parseInt(document.getElementById('value'));
function myFunction() {
alert(Math.sqrt(number));
}
<div class="container">
<form>
<fieldset>
<legend>Number squared</legend>
<p><label >Insert number here: </label><input type="number" id="value"></p>
</fieldset>
<p><input type="button" id="button" onclick="myFunction()" value="calculate"></p>
</form>
</div>

First, document.getElementById() returns an HTML element. You would have to access the value property by doing document.getElementById().value. Second, the number variable will always be equal to NaN since that line of code is executed first and is never changed.
let value = document.getElementById('value').value // Evaluates to ""
let number = parseInt(value); // Evaluates to NaN
// The number variable is never re-evaluated when the function is invoked
function() {
alert(Math.sqrt(number));
}
You would have to move that line of code into your function so that the value of number is determined when the function is called, not at the beginning of code execution.
function myFunction() {
const number = parseInt(document.getElementById('value').value)
if (isNaN(number)) {
alert('Please pass in a number')
return
}
alert(Math.sqrt(number))
}
<div class="container">
<form>
<fieldset>
<legend>Number squared</legend>
<p><label>Insert number here: </label><input type="number" id="value"></p>
</fieldset>
<p><input type="button" id="button" onclick="myFunction()" value="calculate"></p>
</form>
</div>

function myFunction() {
const number = +document.getElementById('value').value;
if (isNaN(number)) {
alert('Please pass in a number')
return
}
alert(Math.sqrt(number))
}

It is because document.getElementById() returns the element itself and not the value. You need to get the value of the input to parse it as integer.
Change the code to parseInt(document.getElementById('value').value);

You must get your element value inside your function call, otherwise you will get NaN(Not a number), like this:
function myFunction() {
let number = parseInt(document.getElementById('value').value);
if(number !== "" && number != undefined && number != null && !isNaN(number)){
alert(Math.sqrt(number));
}else{
alert("Please enter valid number");
}
}
You can also check for undefined, null and empty string values.

Related

Trying a simple compare number script for study assignment [duplicate]

This question already has answers here:
How to get a number value from an input field?
(4 answers)
Closed 1 year ago.
I've been losing my mind now for a couple of hours as I can't find out what I'm doing wrong here. Trying to see if the input is equal to 3, if so then show a window saying "The number is equal to 3".
Here's the HTML and Javascript:
<input type="number" name="number" id="number">
<button id="btn" onclick="checkNumber()">Button</button>
<div>
<span id="label"></span>
</div>
<script>
var number = document.getElementById("number").value;
function checkNumber() {
if (number === 3) {
window.alert("The number is equal to 3");
}
}
</script>
The number variable should typecasted, i.e converted to number type from string type
function checkNumber() {
var number = document.getElementById("number").value;
var value = Number(number);
if (value === 3) {
alert("The number is equal to 3");
} else {
alert("The number is not equal to 3");
}
}
<html>
<body>
<input id="number" name="number" type="number" />
<button id="btn" type="button" onclick="checkNumber()">Check</button>
</body>
</html>
Input value are strings, you can change them to number by adding "+" sign.
var number = document.getElementById("number");
function myFunc() {
if (+number.value === 3) {
window.alert("The number is equal to 3");
}
}
<input type="number" name="number" id="number">
<button id="btn" onclick="myFunc()">Button</button>
<div>
<span id="label"></span>
</div>
<script>
</script>
You are using === which checks both for type and value. the input received from the user is a string while 3 is a Number.
To solve that, you must first convert the input value to Number and then compare.
Also, i would add the reference for the element outside of the function and check for the current value each time the function gets called.
var element = document.getElementById("number");
function checkNumber() {
const numberAsString = element.value;
const number = Number(numberAsString);
if (number === 3) {
window.alert("The number is equal to 3");
}
}
<input type="number" name="number" id="number">
<button id="btn" onclick="checkNumber()">Button</button>
<div>
<span id="label"></span>
</div>

Equality comparison of the input field value not working properly

In the if statement bellow only the else block executes even when the when the answer is 10!
JavaScript
$("#correctOne").hide();
$("#incorrectOne").hide();
function myFunction() {
var inputOne = $("#inputOne").value;
if (inputOne === 10) {
$("#correctOne").show();
} else {
$("#incorrectOne").show();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<h1>What number am I thinking of?</h1>
<p>Divide me by four and my remainder is two. I am net if you see me through the looking glass.</p>
<form>
<input id="inputOne" type="text" placeholder="Answer Here">
<button onclick="myFunction()">submit</button>
</form>
<h2 id="correctOne">Yes!</h2>
<h3 id="incorrectOne">Nope!</h3>
.value is JavaScript and only works for InputElements, you have $("#inputOne'), a jQuery object, and thus need .val().
Next, if you enter 10 into the field, inputOne is "10", not 10, but === also compares type.
Use == instead.
Here is the modified code with code snippet.
I have change .val() instead of .value().
-- Another change is change 10 to "10"
-- Another change is changing == to ===
$("#correctOne").hide();
$("#incorrectOne").hide();
function myFunction() {
var inputOne = $("#inputOne").val();
if (inputOne == "10") {
$("#correctOne").show();
} else {
$("#incorrectOne").show();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<h1>What number am I thinking of?</h1>
<p>Divide me by four and my remainder is two. I am net if you see me through the looking glass.</p>
<form>
<input id="inputOne" type="text" placeholder="Answer Here">
<button onclick="myFunction()">submit</button>
</form>
<h2 id="correctOne">Yes!</h2>
<h3 id="incorrectOne">Nope!</h3>
The syntax is var inputOne ==$('#inputOne).val();
val() is the method to retrieve the value in an element.
html() method can set the inner HTML content too.

How to stop Infinity showing during input

I have created a form which works out a sum depending on the users input, this works fine but during the input stage i get the infinity property displayed in the total. Is there anyway of avoiding this?
I'm by no means a Javascript expecrt so any help would be appreciated. Here is the code.
<div class="wrapper">
<form id="convert">
<input type="text" name="child" onkeyup="formChanged()" onchange="formChanged()"/>
<input type="text" name="parent" onkeyup="formChanged()" onchange="formChanged()"/>
<div id="final"></div>
</form>
<script>
function formChanged() {
var first = document.getElementsByName("child")[0].value;
var second = document.getElementsByName("parent")[0].value;
var third = first / second;
var four = third * 100;
document.getElementById("final").innerHTML = four+"%";
}
</script>
</div><!-- /.wrapper -->
Don't divide by zero.
What you want to do when second is zero is up to you. But probably the easiest way to handle it is to just not do the calculation and not write anything in final unless you have a non-zero value from second.
In addition, you might want to check for NaN as well. If somebody writes a something in either textbox that is not actually a number, you will end up with NaN% in your output. (here you can use isNaN or you can compare the results of parsing your values with NaN).
So you could do something like:
var first = parseFloat(document.getElementsByName("child")[0].value);
var second = parseFloat(document.getElementsByName("parent")[0].value);
if (first !== NaN && second) { // note NaN and 0 are both falsy
// do your calculation here
}
You're going to need to do some validation on your values first. Your calculation only makes sense with numeric values and you're going to have to ensure that you don't try to calculate it if your second variable == 0.
In this case, I wouldn't try to parse/validate the inputs. Do as few as possible, and assume valid inputs.
Just test wether you get a valid output, before showing the result.
function isValidNumber(v){
//!NaN && !Infinity
return v===v && v !== Infinity && v !== -Infinity;
}
//cast the inputs to a valid number
function number(v){
//return +String(v).replace(",", ".");
return +v;
//return +v || 0;
}
function formChanged() {
var first = document.getElementsByName("child")[0].value;
var second = document.getElementsByName("parent")[0].value;
var result = 100 * number(first) / number(second);
document.getElementById("final").innerHTML = isValidNumber(result)?
Math.floor(result) + "%": //I have a valid result
""; //values have changed, but sth. went wrong
}
I think that will work for you.
<div class="wrapper">
<form id="convert">
<input type="text" name="child" onkeyup="formChanged()" onchange="formChanged()"/>
<input type="text" name="parent" onkeyup="formChanged()" onchange="formChanged()"/>
<div id="final"></div>
</form>
<script>
function formChanged() {
var first = document.getElementsByName("child")[0].value;
var second = document.getElementsByName("parent")[0].value;
if(second == ""){second=1};
if(first != "" && second != ""){
var third = parseInt(first) / parseInt(second);
var four = parseInt(third) * 100;
document.getElementById("final").innerHTML = four+"%";
}
}
</script>
</div><!-- /.wrapper -->
Thanks

Javascript number validation function acting up + constructive criticism wanted

So the goal was to make a very simple two field form and use javascript to validate that only numeric values are entered in either field.
Two issues with my code: only the else condition of the functions that follow seems to execute. Even more confusingly it also executes just clicking in the other field when the fields are empty.
Help please?
The Javascript:
// 1. Validate that only a numeric value is entered
function validateMin() {
var min = document.getElementById("min").value;
if (isNaN(min)) {
var el1 = document.getElementById("valFailMin");
el1.textContent = "Ok";
} else {
var el1 = document.getElementById("valFailMin");
el1.textContent = "Only numbers";
}
}
function validateMax() {
var max = document.getElementById("max").value;
if (isNaN(max)) {
var el2 = document.getElementById("valFailMax");
el2.textContent = "Ok";
} else {
var el2 = document.getElementById("valFailMax");
el2.textContent = "Only numbers please";
}
}
The HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="custom.css">
</head>
<body>
<div class="myForm">
<label for="min">Min</label><input id="min" type="number" placeholder="Type a min value" onblur="validateMin()"/><br>
<span id="valFailMin"></span>
</div>
<div class="myForm">
<label for="max">Max</label><input id="max" type="number" placeholder="Type a max value" onblur="validateMax()" /><br>
<span id="valFailMax"></span>
</div>
<div id="valSuccess"></div>
</body>
<script src="validate.js"></script>
</html>
isNaN() returns true, if the checked value is not a number, if it is a number, the return value is false. Also the argument is internally coerced to a number before checking it. In this coercion an empty string is evaluated to 0, which is a number, hence the check returns false.
A fix would be to add a not operator to the condition and detect empty value:
if (!isNaN(min) && min !== '') {...}
A general way to check, if a variable is a number:
var isNumber = (!isNaN(+variable) && isFinite(+variable));
In your function:
if (isNaN(min)) {
var el1 = document.getElementById("valFailMin");
el1.textContent = "Ok";
isNaN returns true if the value isn't a number, so this will return "Ok" where min isn't a number. Depending on the type of number you are after, a regular expression may be more appropriate:
if (/^\d+\.?\d*$/.test(min)) {
// min is an integer or float
}
This will return true for values like '5' or '12.3' but false for valid numbers like '1.23e4'.
The number validation function should be separate from the function to validate the fields, so:
function validNumber (value) {
return /^\d+\.?\d*$/.test(value);
}
Then the validation can be something like:
function validateNumberField(el) {
var errField = document.getElementById(el.id + 'Err');
errField.textContent = validNumber(el.value)? 'Ok' : 'Fail';
}
if you pass this from the listener and link the id (or name) of the input being checked to its related error field.
Some markup (simplified for posting):
Min<input id="min" type="number" placeholder="Type a min value"
onblur="validateNumberField(this)"><br>
<span id="minErr" style="color:red"></span><br>
Max<input id="max" type="number" placeholder="Type a max value"
onblur="validateNumberField(this)"><br>
<span id="maxErr" style="color:red"></span>
You may want to allow for an empty value and to remove leading and trailing white.

set of passwords in arrays, the user only has 3 chances

I need to make an array of passwords looping for the user to be redirected to another site. After 3 mistakes the user cannot try again. This is what I have so far, but it doesn't work.
<form>
<label>Please enter Password</label>
<input type="text" id="Pass" />
<input type="button" value="go" onClick="check()" />
</form>
<script type="text/javascript">
function check()
{
var password = ["123","456","789"]
for(a=0;a=password.length;a++)
{
if (user="password")
{
document.location.href="http://yahoo.com";
}
else
{
alert("wrong password");
}
}
}
</script>
As you are calling a function check from the onclick event, you need a function by that name in your code.
When calling the check function you can pass along the value from the text box, so that the function can use it to check against the items in the array.
In your code the condition for the loop is wrong. Using a=password.length means that the loop won't run at all. The loop runs as long as the condition is true, it's not used to mark the end of the loop.
Use the == operator to check if two values are equal (the = operator is for assignment). Use password[a] to get the item from the array which has the index from the variable a.
In the loop you should only check for when the strings are equal. If you have an else case there, it will tell you that the password is wrong for every password that didn't match. Use return to exit from the function when you have set the location.
After the loop you know that none of the password matches, so then you know that the password was wrong.
<body>
<form>
<label>Please enter Password</label>
<input type="text" name="Pass" />
<input type="button" value="go" onclick="check(this.form.Pass.value)"/>
</form>
<script type="text/javascript">
var password = ["123","456","789"];
function check(pass) {
for(a = 0; a < password.length; a++) {
if (pass == password[a]) {
document.location.href="http://yahoo.com";
return;
}
}
alert("wrong password");
}
</script>
</body>

Categories

Resources