JavaScript Set Default Value on Function Not Working? - javascript

Function in JS
function punch(){
var a,b,result;
a=document.getElementById('n1').value;
b=document.getElementById('n2').value;
var x=parseInt(a);
var y=parseInt(b);
result=x+y;
if (result===NaN)
result =0;
I know this condtition is false and it gives output of x+y. On empty fields it always return NaN value
when change it to
if (result!==NaN)
result=0;
Now it becomes true but it gives x+y also 0.
document.getElementById('n3').value=result;
}
HTML Code
<input type="text" id="n1" placeholder="Value 1"/>
<input type="text" id="n2" placeholder="Value 2"/>
<button type="button" onClick="punch()">Click For Answer</button>
<input type="text" id="n3" placeholder="Answer"/>

Nothing, including NaN, is ever === to NaN. In fact one way to test for NaN is to exploit that!
if (result !== result)
result = 0; // must have been NaN!
You can also use isNaN():
if (isNaN(result))
result = 0;

Related

Unsure why my math min function is not working but math max function is in script code

function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber, valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
selectMinNumber = Math.min(+valueFirstNumber, +valueSecondNumber, +valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML = selectMinNumber;
}
<main class="fancy-border">
<form id="userNumberEntry">
<p><label for="txtFirstNumberValue">Enter your first number here:</label>
<input type="text" id="txtFirstNumberValue" maxlength="20" size="20"></p>
<p><label for="txtSecondNumberValue">Enter your second number here:</label>
<input type="text" id="txtSecondNumberValue" maxlength="20" size="20"></p>
<p><label for="txtThirdNumberValue">Enter your third number here:</label>
<input type="text" id="txtThirdNumberValue" maxlength="20" size="20"></p>
<p><input type="button"
value="Find the highest number"
id="btnSubmit"
onclick="selectHighestNumber();">
</p>
<p><input type="button"
value="Find the lowest number"
id="btnSubmit"
onlick="selectLowestNumber();">
</p>
<br>
<div id="selectRankingNumbersResults">
</div> <!--end of selectRankingNumberValues div-->
</form>
</main>
So very recently I came into a problem in my script where I was unsure why my Math min function was not working. I asked about that issue in a previous question and found that a spelling error was causing one of my functions to not work. Essentially, I have two functions, a math min, and a math max, both serving similar purposes. I am working in Html code, and use a script for my functions within my Html document. The purpose of this math min and math max function is that I have three text boxes to input numbers into, there are two buttons that will either serve to show the highest or lowest of these three values. My math max function works fine and shows the highest value, however, my math min function does not. It does not return any value at all. I have cross-checked my code to see if it was misspelled, spacing errors, or other mismatched words with the rest of my code but none of it seems to be the problem. This is how my math max and math min functions in my script look respectively.
function selectHighestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMaxNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMaxNumber;
}
function selectLowestNumber()
{
var valueFirstNumber;
var valueSecondNumber;
var valueThirdNumber;
var selectMinNumber;
valueFirstNumber = document.getElementById("txtFirstNumberValue")
.value;
valueSecondNumber = document.getElementById("txtSecondNumberValue")
.value;
valueThirdNumber = document.getElementById("txtThirdNumberValue")
.value;
selectMinNumber = Math.min(valueFirstNumber, valueSecondNumber,
valueThirdNumber);
document.getElementById("selectRankingNumbersResults").innerHTML =
selectMinNumber;
}
If anyone could help me understand where I might be going wrong, that would be greatly appreciated! I am very confused about what I could have coded wrong, so any insight/outlook is greatly appreciated!
Math.max and Math.min will return the largest/smallest value (or -Infinity/Infinity if no values are supplied) and then convert to a number if they're not already, this means that strings will first be compared as strings and not numbers ("123" > "3"), so you should first convert each value to a number.
Also I recommend batching up the whole process instead of getting each element separately, reading its value, converting it to a number, checking it's valid, passing it to the function. So try to do the whole thing in a loop of some sort.
document.querySelector("form").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Max:" + getEdgeCase(true));
console.log("Min:" + getEdgeCase(false));
});
function getEdgeCase(flag) {
// get all the inputs in one go and convert them to an array
var inputList = [].slice.call(document.querySelectorAll("form input[type=\"number\"]"));
var inputList = inputList.map(function(input) {
// convert to number, if it's not a valid number and ends up as NaN then return 0
return +input.value || 0;
});
// get the right function and call apply (spreads an array into arguments)
return Math[flag ? "max" : "min"].apply(Math, inputList);
}
<form>
<input type="number" />
<input type="number" />
<input type="number" />
<input type="submit" />
</form>

How can i avoid NaN error at simple form?

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.

How to sum up all dynamic inputs in js

How can I get all the sum of these inputs? Sometime they have a value from the database, sometimes no value and needs to be inputted. I'm using jquery for this.
Please see the code below:
$(document).ready(function(){
$('input[name=grade\\[\\]]').on('focus, keyup', function(){
var points = $('input[name=grade\\[\\]]');
var totals = points.get()
.map(function(sel){
return parseFloat(sel.value, 10);
})
.reduce(getSum, 0);
if(points.length == 1){
$('input[name=total]').val($(this).val());
} else if(points.length > 1 && totals < 100){
$('input[name=total]').val(totals);
}
});
function getSum(total, value){
return total + parseFloat(value, 10);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="grade[]" ><br><br>
<input type="text" name="grade[]" ><br><br>
<input type="text" name="grade[]" ><br><br>
<input type="text" name="grade[]" ><br><br>
<input type="text" name="grade[]" ><br><br><br>
Total<br>
<input type="text" name="total" readonly>
</form>
The problem is that parseFloat() returns NaN when the value can't be parsed as a number, and the result of adding up a list that includes some NaN values will be NaN. Which means your if/else that decides whether to display the total won't display it because NaN < 100 is false.
Given that your inputs are empty to start with those items are parsed as NaN.
The simplest fix is to change this line in your .map() function:
return parseFloat(sel.value, 10);
to be:
return parseFloat(sel.value) || 0;
...where the || operator will return the left-hand operand if it is a truthy value, i.e., a number, not NaN or 0, and otherwise return the right-hand operand 0. That is, blank or otherwise non-numeric values will be treated as if they were 0.
You don't need to call parseFloat() again in your getSum() function, because by then you already have numbers.
(Note also that parseFloat() doesn't take a second argument, you've mixed that up with parseInt().)
$(document).ready(function() {
$('input[name=grade\\[\\]]').on('focus, keyup', function() {
var points = $('input[name=grade\\[\\]]');
var totals = points.get()
.map(function(sel) {
return parseFloat(sel.value) || 0; // <-- this is the line that changed
})
.reduce(getSum, 0);
if (points.length == 1) {
$('input[name=total]').val($(this).val());
} else if (points.length > 1 && totals < 100) {
$('input[name=total]').val(totals);
}
});
function getSum(total, value) {
return total + value; // <-- no need for parseFloat() here
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="grade[]">
<input type="text" name="grade[]">
<input type="text" name="grade[]">
<input type="text" name="grade[]">
<input type="text" name="grade[]"><br><br><br> Total
<br>
<input type="text" name="total" readonly>
</form>
(I've removed most of the <br> elements just to avoid having to scroll down to see the total for demo purposes.)

Trouble getting count of negative number

I have several inputs in the same class and a function that returns false if any of these inputs are empty. What I am trying to do is return false if any of the inputs are negative numbers. I think there might be a way to do this using a regex but am unsure how to go about it.
This is what I have so far.
var $nonneg = $('.quantity').filter(function(){
return this.value < 0;
});
if ($nonneg.length != 0) {
return false;
}
Probably it should be return this.value =='';
The idea is to check if the value for 3 conditions:
equal === to empty string ""
If coercing the value to a Number results in NaN
If the number (when coerced) is less than zero.
You can use Array.prototype.some() to check your conditions and return the value. Here's an example of how it can work:
$(".check-inputs").on("click", function () {
console.log(anyInvalid());
});
function anyInvalid () {
return Array.prototype.some.bind($(".quantity"))(function (elem) {
return elem.value === "" || isNaN(Number(elem.value)) || Number(elem.value) < 0;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="quantity" value="1"/><br/>
<input type="text" class="quantity" value="2"/><br/>
<input type="text" class="quantity" value="3"/><br/>
<input type="text" class="quantity" value="-4"/><br/>
<input type="text" class="quantity" value=""/><br/>
<button class="check-inputs">Check Inputs</button>
I found a solution that works for me, it returns false if it finds a number less than zero. I was making it out to be more complex than it should have been.
var $nonneg = $('.quantity').filter(function(){
return this.value < 0;
});
if ($nonneg.length != 0) {
return false;
}
Use the Array.prototype.every() function to check that every input in the array passes a given test. First, get the inputs as an array using jQuery's .get(). Then run the elements through Array.prototype.every and it will return false if any elements fail the given test.
function arePositiveOrZero(selector){
return $(selector)
.get() // Convert to array
.every( node => parseInt(node.value) >= 0 ) // Check all elements are >= 0
}
// Tests that log to the console
console.log({hasNeg: arePositiveOrZero('.hasNeg')}) // false
console.log({hasBlank: arePositiveOrZero('.hasBlank')}) // false
console.log({hasZero: arePositiveOrZero('.hasZero')}) // true
console.log({allPos: arePositiveOrZero('.allPos')}) // true
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="hasNeg" type="text" value="1">
<input class="hasNeg" type="text" value="-1">
<input class="hasZero" type="text" value="0">
<input class="hasZero" type="text" value="1">
<input class="hasBlank" type="text" value="1">
<input class="hasBlank" type="text" value="">
<input class="allPos" type="text" value="2">
<input class="allPos" type="text" value="3">
If you don't want to include zero, just change the test function to node => node.value > 0

Javascript Addition Error Message

I am new to javascript and was wondering what the the following error message means:
Hello __ NaN
What does NaN mean?
My script is as follows:
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("What Is Your Name?");
return false;
}
}
function addNos(){
var a, b, res;
a= parseFloat(document.myForm.salary.value);
b= parseFloat(document.myForm.requiredamount.value);
res = a+b;
window.alert("Hello" + a + b );
}
</script>
<form name="myForm" action="" onsubmit="return validateForm()" method="post">
<label>Your Name</label> <br /><br /><input name="name" type="text" />
<br /><br />
<label>Your Salary</label><br /><br />
<select name="salary">
<option value="10000">10000</option>
<option value="20000">20000</option>
<option value="30000">30000</option>
</select>
<br /><br />
<label>Required Amount</label><br /><br />
<input name="requiredamount" type="radio" value="5000" /> 5000
<input name="requiredamount" type="radio" value="10000" /> 10000
<input name="requiredamount" type="radio" value="15000" /> 15000
<input name="requiredamount" type="radio" value="20000" /> 20000
<br /><br />
<input name="" type="submit" value="Get Quote" onclick="addNos()" />
</form>
i am trying to add the requiredamount with the salary and also get the name to appear in the dialog box.
anyone know the anwseR?
function addNos(){
var a, b, res;
a= parseFloat(document.myForm.salary.value);
b= parseFloat(document.myForm.requiredamount.value);
res = a+b;
window.alert("Hello" + a + b );
}
You are relying on user input to be properly entered as a number. You should validate that the input is a number using a RegEx before parsing.
http://jsfiddle.net/rMgeB/
It means "Not a Number" (NaN). This will happen if either the "salary" field or the "requiredamount" field has some non-numeric value in it. For instance if you had the values "100" and "Blah" repsectively, the parseFloat() used to calculate a would return the number 100 and the parseFloat() for b would return NaN since "Blah" has no numeric representation. Subsequently when you try to add 100 and NaN in your alert box, you'll get the behavior you're seeing.
You can double check these values by using the isNaN() function:
a = parseFloat(...);
if (isNaN(a))
{
alert("Sorry, you must enter a real number");
return;
}
Hope that clears things up.
EDIT:
What's most likely the case is that your input has a $ in it. parseFloat("$100") == NaN whereas parseFloat("100") == 100 so you'll need to strip any leading dollar signs in your code first.
Try this:
http://jsfiddle.net/LEX84/
I did not add a test if a radio button is selected. NaN will be the result if no radio button is selected.
Obtaining the radio button is from here: javascript selected radio
function validateForm()
{
var x=document.forms["myForm"]["name"].value;
if (x==null || x=="")
{
alert("What Is Your Name?");
return false;
}
}
function getCheckedRadioId(name) {
var elements = document.getElementsByName(name);
for (var i=0, len=elements.length; i<len; ++i)
if (elements[i].checked) return elements[i].value;
}
function addNos(){
var a, b, res;
a= parseFloat(document.myForm.salary[document.myForm.salary.selectedIndex].value);
alert(a);
b= parseFloat(getCheckedRadioId("requiredamount"));
res = a+b;
window.alert("Hello " + a + " " + b );
}
NaN means Not a Number. It can happen when dividing by zero, or adding an undefined value.
Wiki:
http://en.wikipedia.org/wiki/NaN
Ok i've not got the time to test your code, but it looks like your JavaScript is trying to access the form elements before the user has entered a value? (meaning they're undefined).
need to download jQuery to do this:
You could surround your JavaScript code in $(document).ready(function(){ //your code {);
How to detect causes of NaN
Has the html element loaded (sometimes the html loads after the javascript)
Is the value undefined?
Are you dividing by zero?
JavaScript has http://www.w3schools.com/jsref/jsref_isnan.asp

Categories

Resources