Javascript Addition Error Message - javascript

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

Related

Basic math functions in JavaScript to show on HTML page

I would like to make major of basic math functions (addition, subtraction, ect.) to develop in JavaScript. Input parameters should be from HTML webpage, than do the in JavaScript and return result on the same HTML page.
function math() {
//document.getElementById("frm1").innerHTML;
var numb = document.getElementById("number").innerHTML;
var mod = document.getElementById("modifier").innerHTML;
console.log(numb);
console.log(mod);
var sum = 1; //numb + mod; //the 1 is a placeholder
console.log(sum);
sum = document.getElementById("sum").innerHTML;
}
<form id="frm1" action="randScript.js">
Number: <input type="int" name="number" id="number"><br> Modifiers: <input type="int" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id="sum"></p>
Your form tag has an action attribute. This means the page will submit your information to the specified page. You can use jQuery to prevent the form from submitting.
$("#yourFormId").on("submit",function(event){event.preventDefault()})
You can also edit the forms action attribute itself to prevent it from submitting.
<form id="frm1" action"javascript:void(0);">
First: The type is text - there is no "int" thing
Number: <input type="text" name="number" id="number">
Second: if we read a bit documentation we figure also out how to get the alue into the JS part
var numb = document.getElementById("number").value;
here you can now do your further homework ;)
Third: Get things back:
either use another input. They work two ways.
document.getElementById("result").value="I did not do my homework alone"
or you place a div somewhere with an id
<div id="result"> </div>
and now you can really use innerHTML in js
document.getElementById("result").innerHTML="I am too lazy";
The rest and to put it all together is now up to you :) Have fun to study :)
Try that if you want to display the sum at the html element:
document.getElementById("sum").innerHTML = sum;
But a more precise Question would help!
There is no int type for form inputs in HTML you can learn here about input types: HTML form input types
<form id="frm1" >
Number1: <input type="number" name="number" id="number1"><br>
Number2: <input type="number" name="number" id="number2"><br>
Modifiers: <input type="text" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id = "sum"></p>
<script type="text/javascript">
function math() {
var numb1 = parseInt(document.getElementById("number1").value);
var numb2 = parseInt(document.getElementById("number2").value);
var mod = document.getElementById("modifier").value;
if(mod == '+'){
var sum = numb1 + numb2;
}else if(mod == '-'){
var sum = numb1 - numb2;
}else if(mod == '*'){
var sum = numb1 * numb2;
}
if(sum === undefined){
alert('invalid inputs');
return false;
}else{
document.getElementById("sum").innerHTML = sum;
}
return true;
}
To retrieve inputs values properly use value rather then innerHtml.
Retrieved values are strings so you need to parse them to numbers (with parseInt) before using them in math.
function math() {
const numb = document.getElementById("number").value;
const mod = document.getElementById("modifier").value;
sum = document.getElementById("sum").innerText = parseInt(numb) + parseInt(mod);
}

I want to restrict users from entering number ending with 5

Here is text field.I want users to only enter value like 210,220,230,... and restrict from entering something like 215,225,...
I am looking for suggetions.I don't have much knowledge of javascript.
If you just want to prevent strings that end in '5':
document.getElementById("input").onblur = checkEND;
function checkEND() {
let firstValue = event.currentTarget.value;
if(firstValue.endsWith('5')){
warnUser()
}
}
This won't validate that the string is a valid number though.
function testInput() {
var key = window.event.keyCode;
var x = document.getElementById('textarea').value
var y = document.getElementById('textarea2').value
var z = parseInt(x, 10);
if (z+10 == y) {
document.getElementById('result').innerHTML = "valid";
} else {
document.getElementById('result').innerHTML = "invalid";
}
}
<textarea maxlength="3" id="textarea">5</textarea>
<textarea maxlength="3" id="textarea2">15</textarea>
<button onclick="testInput()">Test Input</button>
<div id="result"></div>
The first input is your first number, the second is your second number.
See Comments If Your Wondering Why This Doesn't Answer His OG Question
You can experiment with the setCustomValidity() of input elements (https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) from an onblur, onchange or oninput handler. If you are not satisfied with the value, set an error message, and an empty string otherwise. As long as the error message is set to non-empty, it is displayed and the form refuses to submit:
function check5() {
cgiftcardq.setCustomValidity(cgiftcardq.value.endsWith('5')?"Nope, it can not end with 5":"");
}
<form>
<input name="cgiftcardq" class="text_field" id="cgiftcardq" size="3" autocomplete="off" type="text" onblur="check5()">
<input type="submit" value="Send">
</form>
(StackOverflow snippets interfere with form submission - probably as part of security -, so successful submission just makes the form disappear)
As setCustomValidity() does not work everywhere (according to the compatibility table, it will not work on non-Andorid mobiles), classic "budget" solution may be mentioned too: you can simply disable the send button as long as you are not satisfied with the input:
function check5() {
if(cgiftcardq.value.endsWith('5')){
send.disabled=true;
message.innerHTML="Nope, it can not end with 5";
} else {
send.disabled=false;
message.innerHTML="OK";
}
}
<form>
<input name="cgiftcardq" class="text_field" id="cgiftcardq" size="3" autocomplete="off" type="text" oninput="check5()">
<input id="send" type="submit" value="Send" disabled>
</form>
<div id="message"></div>

Javascript onkeypress conditions

I'ts my first time exploring java script,Can you help me? thanks in advance
I have a problem in conditioning textboxes.
I have 2 textboxes, the textbox1 and the textbox2, I want the textbox2 to alert me a message on a onkeypress only if textbox2 is greater than textbox1. I succeeded it but the output is not what I expected. so here is what I have done.
//javascript
function validation()
{
x = Number(document.getElementById('text1').value);
y = Number(document.getElementById('text2').value);
if(x < y)
{
alert('Invalid');
return false;
}
}
<!-- HTML -->
<html>
<body>
Text1:<input type="text" id="text1" /><Br />
Text2:<input type="text" id="text2" onkeypress="return validation()" />
</body>
</html>
so the result is this:
Text1:10
Text2:11
when the text2 is 3 digits e.g. 110 the alert message appear, it should appear when I enter 11 because text1 < text2 Am I missing something? or I'm just an idiot.
actually it get called on first character, and works corectly for third one, so use onchange
<input type="text" id="text2" onchange="return validation()" />
eventually you will have to decide the console.log instead of alerting as it blocks you testing way.
you can see this example:
http://jsfiddle.net/yonatanalexis22/yxub03yt/1/
var text2 = document.getElementById('text2');
text2.onchange = function(){
x = Number(document.getElementById('text1').value);
y = Number(this.value);
if(x < y)
{
alert('Invalid');
}
}
First: Your inputs are "text". If you want to compare numbers, change the type of the input to "number".
Second: Adding a Listener is a cleaner way of handling this.
So the HTML could look like this:
Text1:<input type="number" id="text1" /><Br />
Text2:<input type="number" id="text2"/>
And your JavaScript like this:
document.getElementById("text2").addEventListener("change", function() {
if($('#text1').val() < $('#text2').val()) alert();
});
This is just a short version.
Here is the JSFiddle.

Grab form fields and calculate based on inputs

I'm getting an undefined error and don't know why this isn't working.
It's supposed to divide the rent by the amount of roommates:
function splitRent() {
var roommates = document.getElementById("rent");
var rent = document.getElementById("rent");
var rentEach = rent / roommates;
if (document.getElementById("submit") == true) {
document.write("You each should pay" + " " + rentEach)
} else {
document.alert("Gimme info")
}
};
<h1>Roommate Room Splitter</h1>
<form id="myForm">
Roommates:
<input type="text" name="roommates" id="roommates">
<br/>Rent:
<input type="text" name="rent" id="rent">
<br/>
<input type='submit' id='submit' value='Submit' onclick="splitRent()" />
</form>
You want to take the value of the fields, not the fields themselves.
document.getElementById() returns the node, but you want the value of the input field:
var rent = document.getElementById("rent").value;
Also, you're getting the value of the rent twice; you want to check the roommates as well.
var roommates = document.getElementById("roommates").value;
Lastly, document.getElementById("submit") == true doesn't mean anything: you're comparing a button node with a boolean value, which doesn't make sense. If you want to check to make sure that both fields are filled, try this:
if(roommates && rent){
//do calculations
}else{
window.alert("Enter something"); //note that it's window.alert(), not document.alert(), which is not a function
As it stands, this allows people to enter things that are not numbers; there are two things that you could do to fix that.
Use parseInt()/parseFloat() to ensure that you're extracting a number
Check that you actually have a number before doing calculations
You'd do something like this:
var rent = parseInt(document.getElementById("rent").value);
var roommates = parseFloat(document.getElementById("rooommates").value);
If you use the checking I've done above (rent && roommates), the validation will take place there (it checks for both empty and NaN values).
function splitRent() {
var roommates = parseInt(document.getElementById("roommates").value);
var rent = parseFloat(document.getElementById("rent").value);
var rentEach = rent / roommates;
if (roommates && rent) {
document.write("You each should pay" + " " + rentEach)
} else {
window.alert("Gimme info")
}
};
<h1>Roommate Room Splitter</h1>
<form id="myForm">
Roommates:
<input type="text" name="roommates" id="roommates">
<br/>Rent:
<input type="text" name="rent" id="rent">
<br/>
<input type='submit' id='submit' value='Submit' onclick="splitRent()" />
</form>
Shouldn't this be:
var roommates = document.getElementById("roommates").value;
var rent = document.getElementById("rent").value;
Do you always get "1" for your result?

How do I prevent invalid characters from being entered into a form?

For example, if I have a form and I don't want the user to enter numbers in it and I validate it with a function containing a regular expression, how do I prevent the invalid character the user entered (in this example, a digit) from showing up in the text form if it fails the regular expression test?
This is the function I tried and the select list I tried it on (in other words, this isn't the whole program). I tried returning false to the onkeypress event handler but what the user enters into the textbox still goes through.
function noNumbers(answer) { //returns false and displays an alert if the answer contains numbers
if (/[\d]+/.test(answer)) { // if there are numbers
window.alert("You can not enter numbers in this field");
return false;
}
}
<form action="get" enctype="application/x-www-form-urlencoded">
<select id="questions" name="questions">
<option value="no_numbers">What is the name of the city where you were born?</option>
<option value="no_letters">What is your phone number?</option>
<option value="no_numbers">What is the name of your favorite pet?</option>
<option value="no_letters">What is your social security number?</option>
<option value="no_numbers">What is your mother's maiden name?</option>
</select>
<p><input type="text" name="answer" onkeypress="validateAnswer();" /></p>
</form>
This validation works great for stripping invalid characters on the fly as you enter them in the relevant field. Example:
<form id="form1" name="form1" method="post">
Email:
<input type="text" name="email" id="email" onkeyup='res(this, emailaddr);' ; </form>
<script>
var phone = "()-+ 0123456789";
var numb = "0123456789";
var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #-'.,";
var alphanumb = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ #-.'1234567890!?,:;£$%&*()";
var alphaname = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,-.1234567890";
var emailaddr = "0123456789#._abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function res(t, v) {
var w = "";
for (i = 0; i < t.value.length; i++) {
x = t.value.charAt(i);
if (v.indexOf(x, 0) != -1)
w += x;
}
t.value = w;
}
</script>
Then you would simply change the second value of the javascript call to the type of data you want entered in the field using the variables that are defined within the code.
This is the function you are looking for
function validateAnswer(src) {
var questions = document.getElementById("questions");
var rule = questions.options[questions.selectedIndex].value;
if(rule=="no_numbers") src.value = src.value.replace(/\d/g, '');
if(rule=="no_letters") src.value = src.value.replace(/\w/g, '');
}
just send the input field reference to the function and set it to onkeyup event instead:
<input type="text" name="answer" onkeyup="validateAnswer(this);" />
you should also hook the onchange event of the selectbox to reset the value of the input box. I suggest you also consider the HTML5 pattern attribute. See
the fiddle
patern attribute support
workaround for unsupported browsers
You get the key being pressed from the event object passed to the handler.
input type="text" name="answer" onkeypress="validateAnswer(this, event);" />
function validateAnswer(element, event) {
if (event.charCode) {
if (/\d/.test(String.fromCharCode(event.charCode))) {
window.alert("You can not enter numbers in this field");
return false;
}
}
}
Googling for "onkeypress event" finds many examples of this.
Make your life simpler by adding an extra parameter to your validateAnswer function like this:
<input type="text" id="answer" name="answer" onkeyup="validateAnswer(this);" />
Then you can define your validateAnswer like this:
function validateAnswer(elem){
elem.value = elem.value.replace(/[^\d]/g, '');
}
Here an example: http://jsbin.com/iwiduq/1/

Categories

Resources