Why is my alert always showing the wrong information? (addition) - javascript

I'm currently writing some code using both HTML and Javascript. I'm building myself a mini Javascript calculator that can run simple additions using a HTML 'GUI' - if you take it that way. The code is below.
<!DOCTYPE html>
<html lang="en">
<head>
<link href="stylesheet/calculator.css" type="text/css" rel="stylesheet" />
<script>
function activeButton() {
if (document.getElementById("radioAdd").checked === true) {
var valueOne = Number(document.getElementById("number1".value));
var valueTwo = Number(document.getElementById("number2".value));
var result = valueOne + valueTwo;
alert("Your Result Is " + result);
}
}
</script>
</head>
<body>
<div id="wrapper">
<div id="form-move">
<form name = "calculator" id="calculator">
<div id="numberInput">
<input type="number" name="inputNumber1" id="number1" placeholder="Type or Select Your First Number" />
<input type="number" name="inputNumber2" id="number2" placeholder="Type or Select Your Second Number" />
</div>
<div id="radio-input">
<span class="title">Operators:</span>
<input type="radio" name="radioInputAdd" id="radioAdd" value="Addition" />
<label for="radioAdd">Addition</label>
<input type="radio" name="radioInputAdd" id="radioDivision" value="Division" />
<label for="radioDivision">Division</label>
<input type="radio" name="radioInputAdd" id="radioMultiply" value="Multiplication" />
<label for="radioMultiply">Multiply</label>
<input type="radio" name="radioInputAdd" id="radioSubtract" value="Subtraction" />
<label for="radioSubtract">Subtract</label>
</div>
<div class="submit">
<input type="submit" value="Enter" id="submit" onclick="activeButton()" />
</div>
</form>
</div>
</div>
There are TWO input boxes in the middle of the page, which only accept numbers.
Underneath them are four radio buttons - Add, division, Multiply and Subtract. Now, You can see the javascript incorporated at the top of the page. The problem I have is that when I run the page and want to add two numbers, the code works but the answer comes out as 0. I have tested this in chrome and this happens all the time.
Could Someone Possibly please help?

The problem is in how you're trying to get the value from the input elements. In this code:
var valueOne = Number(document.getElementById("number1".value));
var valueTwo = Number(document.getElementById("number2".value));
You're trying to get the value property from the string "number1", which is undefined, then passing that to document.getElementById, which will return null, and then passing that to Number, which will return 0.
Try this this instead:
var valueOne = Number(document.getElementById("number1").value);
var valueTwo = Number(document.getElementById("number2").value);

Try this:
var valueOne = Number(document.getElementById("number1").value);
var valueTwo = Number(document.getElementById("number2").value);
You have the paranthesis in the wrong place.

Related

javascript code not working with html script

hi guys I just begin to learn javascript recently and I came across an issue, when I enter a "10" as the first input element and click submit, it should print a "10" at the bottom of the html page, but instead it prints nothing.
<html>
<head>
<head>
<form action="" method="POST" id="info">
<br>Age:<br><label>
<input name="age" id="age" type="text" placeholder= "enter your age" />
</label>
<br>Sex:<br><label>
female<input name="female" id="female" type="checkbox" />|
male<input type="checkbox" name="male" id="male" />|
</label>
<br>weight:<br><label>
<input type="text" name="weight" id="weight" placeholder="enter your weight in kg" />
</label>
<input type="submit" form="info" value="Submit" onclick="validation()"/>
</form>
<div id="div1"> </div>
<script src = "test.js"></script>
<html>
This is the html code (index.html)
function validation(){
var ageinput = parseInt(document.getElementById("age"));
var femaleinput = ducument.getElementById("female");
var maleinput = ducument.getElementById("male");
var weight = parseInt(document. getElementById("weight"));
var formulaformale;
var formulaforfemale;
var gendererror;
if (ageinput == 10){
gendererror = ageinput
}
document.getElementById("div1").innerHTML = gendererror;
}
this is the javascript code.(test.js)
I tried to find syntax errors but everything looks fine to me, I also compared my code with other people's and I could find anything in my code that is different.I am totally new in javascript so I might have missed certain part of the programming language. please help.
Your button type is submit, so it will always submit and reload the page every time you press the button. Make it a normal button by changing input type to button
<input type="button" form="info" value="Submit" onclick="validation()"/>
Then follow #Ibra answer
// add .value
var ageinput = parseInt(document.getElementById("age").value);
// ducument -> document
var femaleinput = ducument.getElementById("female").value;
Try again like this :
// add .value
var ageinput = parseInt(document.getElementById("age").value);
// ducument -> document
var femaleinput = ducument.getElementById("female").value;

Having Trouble Figuring this code out with if else statements for radio buttons

Hey guys I am having trouble with this
please click that for the instructions.Image did not load in for some reason.
This is my current code, honestly I am confused and dont really know how to approach this. I am new to javascript and was trying to do this as practice for an upcoming exam. I really hope someone can help me figure this out. I know the javascript is not finished and what I currently have is probably wrong but I am just confused on where to take this. Thanks
Function tips() {
var mealCost=parseFloat(document.getElementById("txtMealCost").value);
var Great1= document.getElementById("great");
var Okay2= document.getElementById("okay");
var Poor3= document.getElementById("poor");
var totalCost1= mealCost * .20
if (document.getElementById("great").checked) {
}
}
<h1>Tip Calculator</h1>
<hr>
<span>What was the cost of your meal? </span>
<input type="text" id="txtMealCost" />
<hr>
How would you rate the service?<br>
Great (20%) <input type="radio" name="radServiceQuality" id="great"> <br>
Okay (15%) <input type="radio" name="radServiceQuality" id="okay"> <br>
Poor (10%) <input type="radio" name="radServiceQuality" id="poor"> <br>
<p><input type="button" value="Calculate Tip Amount" onclick="calcTip()">
<div id="output">
</div>
The requirement provided is not clear enough.
Assuming you just need a simple output, what you should do in the function call is,
1.find the value of the selected radio button
document.querySelector('input[name="radServiceQuality"]:checked').value
2a. Decide the tip ratio
if (selected_value = 'great') tip_percentage = 0.2;
2b. Calculate the tip
tip = meal_cost * tip_percentage;
3.output the tip
alert(tip);
You should go through some javascript basic tutorial. And keep on googling.
You can do something like this,
// es6 style function, same as "function(){...}"
tips = () => {
// Getthe selected radio
let selected = document.querySelector(`input[name='radServiceQuality']:checked`);
// If a radio is selected
if (selected) {
// Cast as number
var mealCost = +document.getElementById("txtMealCost").value;
// Format the number as curency
let totalCost = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(selected.value * mealCost);
// Set output string
document.getElementById('output').innerText = totalCost;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>IT-130 Exam</title>
</head>
<body>
<h1>Tip Calculator</h1>
<hr>
<span>What was the cost of your meal? </span>
<input type="text" id="txtMealCost" />
<hr> How would you rate the service?
<br> Great (20%) <input type="radio" id='great' name="radServiceQuality" value=".2">
<br> Okay (15%) <input type="radio" id='okay' name="radServiceQuality" value=".15">
<br> Poor (10%) <input type="radio" id='poor' name="radServiceQuality" value=".1"> <br>
<p><input type="button" value="Calculate Tip Amount" onclick="tips()">
<div id="output"></div>
</body>
</html>
IFF the HTML is not allowed to be changed, this shall do the trick:
// Helper function to determine percent to apply
getPercent = selectedId => {
switch (selectedId) {
case 'great':
return .2;
case 'okay':
return .15;
case 'poor':
return .1;
}
};
// es6 style function, same as "function(){...}"
calcTip = () => {
// Getthe selected radio
let selected = document.querySelector(`input[name='radServiceQuality']:checked`);
// If a radio is selected
if (selected) {
// set percent
let percent = getPercent(selected.id);
// Cast as number
var mealCost = +document.getElementById("txtMealCost").value;
// Format the number as curency
let totalCost = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(percent * mealCost);
// Set output string
document.getElementById('output').innerText = totalCost;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>IT-130 Exam</title>
</head>
<body>
<h1>Tip Calculator</h1>
<hr>
<span>What was the cost of your meal? </span>
<input type="text" id="txtMealCost" />
<hr> How would you rate the service?<br> Great (20%) <input type="radio" name="radServiceQuality" id="great"> <br> Okay (15%) <input type="radio" name="radServiceQuality" id="okay"> <br> Poor (10%) <input type="radio" name="radServiceQuality" id="poor"> <br>
<p><input type="button" value="Calculate Tip Amount" onclick="calcTip()">
<div id="output">
</div>
</body>
</html>
Hope this helps,

JavaScript How to Get Keyboard to Push() new Input via Buttons

The title is kinda confusing because I find it hard to explain. Basically, I can get 1 input button to have one id name that a JavaScript function will store into a variable and display it by replacing an empty paragraph tag with the variable. However, I can't get it to work with multiple buttons with the same function, since I'm trying to get a number keypad going with buttons, and having it display the result. I think I need to use the push() method to somehow add values, then click a submit button, then have the resulting string displayed. I know how to use push with known variables, but I don't know how to implement it with unknown variables, though:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
Anyways, my code is here, with the input buttons with only 1 button with the i, and etc. jQuery answers are welcome, but I don't prefer jQuery, as I'm asking about JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>Desperate</title>
<script type="text/javascript">
function othername() {
var inputinput = document.getElementById("userInput").value;
var n = inputinput.length;
document.getElementById("demo").innerHTML = n;
}
</script>
</head>
<body>
<p id="demo"></p>
<input id="text" type="text">
</div>
<div>
<input id="userInput" type="button" value="1" onclick="othername();" />
<input id="btn2" type="button" value="2" onclick="othername();" />
<input id="btn3" type="button" value="3" onclick="othername();" />
</div>
</body>
</html>
All help is greatly appreciated! Thank you!
You should bind your onclick event handler in a different way. Then you can examine the incoming event in your "othername" function and get the value of the element clicked.
<!DOCTYPE html>
<html>
<head>
<title>Desperate</title>
<script type="text/javascript">
function othername(e) {
var n = e.srcElement.value || '';
document.getElementById("demo").innerHTML = n;
}
</script>
</head>
<body>
<div>
<p id="demo"></p>
<input id="text" type="text">
</div>
<div id="btns">
<input id="userInput" type="button" value="1" />
<input id="btn2" type="button" value="2" />
<input id="btn3" type="button" value="3" />
</div>
<script>
var btnC = document.getElementById("btns");
btnC.onclick = othername;
</script>
</body>
</html>

Javascript won't output values from input box

I want to user to press submit button so that their name and age is displayed in the input box with name="output"?
I have 3 input boxes, one asking for name and the other for age while the other one provides output. I am trying to use the function output() to display the last input box.
I am confused about where I am going wrong, do I need a .value?
<!doctype html>
<html>
<head>
<style>
.formdiv{
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output(){
var name = getElementByName('firstName');
var Age= getElementByName('age');
var out = document.write(name+Age);
document.getElementByName('output') = out;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset><center>
<legend> Enter the following Info:</legend>
<br />
<label> Name </label>
<input type="text" name="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age </label>
<input type="number" name="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button><br/>
<label for="output">Output</label>
<br/>
<input type="textbox" name="output"></input>
</center>
</div>
</body>
</html>
Here's a working version of your code.
There's no method getElementByName (but getElementsByName) - you should use document.getElementById() (Read about it here)
You should use the value of the input element.
<!doctype html>
<html>
<head>
<style>
.formdiv{
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output(){
var name = document.getElementById('firstName').value;
var Age= document.getElementById('age').value;
document.getElementById('output').value = name+Age;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset><center>
<legend> Enter the following Info:</legend>
<br />
<label> Name </label>
<input type="text" id="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age </label>
<input type="number" id="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button><br/>
<label for="output">Output</label>
<br/>
<input type="textbox" id="output"></input>
</center>
</div>
</body>
</html>
getElementsByName (note: Elements, not Element) returns a list of Elements, in this case your <input>s. So first of all, you need to select the first (in your case your only one) using getElementsByName(...)[0]. Then you get one Element.
However you do not want to output the entire element (which is an Object, not a String, and converted to a string it likely won't be what you expect), so you need to select the value property of that Element. So yes, you need to add .value, just as you assumed:
function output(){
var name = getElementsByName('firstName')[0].value;
var Age= getElementsByName('age')[0].value;
Then, document.write writes the argument to a new document directly, which results in an emtpy page with nothing else on it but that string. This isn't what you want, so you don't need that. ALl you do want is to assign a new variable called out with that string:
var out = name+Age;
Then to assigning the new value to the output field - you don't want to replace the Element by a string (that wouldn't even work), but it's value, so you need the .value again:
document.getElementsByName('output')[0].value = out;
}
That should do the trick.
(In addition to that, you might want to use name + " " + Age instead of simply name+Age, as otherwise you end up with "John Doe23" instead of "John Doe 23" which you likely want)
There are a few things wrong with your code:
there is no such thing as getElementByName - it is getElementById
changing to the above, you need to add ids to your input elements
you need to use the value of the returned object from getElementById
The above will get your code working, but also, the center tag is obsolete and you shouldn't use it
Inputs are self closing tags so you don't need </input>
<!doctype html>
<html>
<head>
<style>
.formdiv {
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output() {
var name = document.getElementById('firstName').value;
var Age = document.getElementById('age').value;
var out = name + Age;
document.getElementById('output').value = out;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset>
<center>
<legend>Enter the following Info:</legend>
<br />
<label>Name</label>
<input type="text" name="firstName" id="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age</label>
<input type="number" name="age" id="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button>
<br/>
<label for="output">Output</label>
<br/>
<input type="textbox" name="output" id="output"></input>
</center>
</div>
</body>
</html>

Get numerical values from input fields and use them to calculate the surface area of a trapezoid

I am new to Javascript and I will be thankful if someone help me understand what I am doing wrong. I am trying to calculate the surface area of a trapezoid by obtaining values from input fields. When I press the "Calculate S" button I get a "Nan" as an answer.
This is the major part of the HTML code:
<form method="post">
<label for="a">a</label>
<input type="text" id="a"/> <br/>
<label for="b">b</label>
<input type="text" id="b"/> <br/>
<label for="h">h</label>
<input type="text" id="h"/> <br/>
<button onclick="alert(S)">Calculate S</button>
</form>
And this is the script I am using to obtain the values and calculate the surface:
<script type="text/javascript">
var a=parseInt(document.getElementById("a"), 10);
var b=parseInt(document.getElementById("b"), 10);
var h=parseInt(document.getElementById("h"), 10);
var S=parseInt(((a+b)/2)*h, 10);
</script>
Thanks in advance!
You need to get the value out of each input, not just the input, like this:
<script type="text/javascript">
var a=parseInt(document.getElementById("a").value, 10);
var b=parseInt(document.getElementById("b").value, 10);
var h=parseInt(document.getElementById("h").value, 10);
var S=((a+b)/2)*h;
</script>
Use .value property on the input elements to get their contents. then call parseInt on that to get a number.
No need to parseInt the result too.
var S = ((a + b) / 2) * h;
Wrap the code in a callable function if you want it executed on button click (what you have now will execute when the code been parsed by your browser).
Example found here: http://jsfiddle.net/bpwEh/
Updated code:
<head>
<!-- ... -->
<script>
function calc(){
var a=parseInt(document.getElementById("a").value, 10);
var b=parseInt(document.getElementById("b").value, 10);
var h=parseInt(document.getElementById("h").value, 10);
return ((a+b)/2)*h, 10;
}
</script>
</head>
<body>
<form method="post">
<label for="a">a</label>
<input type="text" id="a"/> <br/>
<label for="b">b</label>
<input type="text" id="b"/> <br/>
<label for="h">h</label>
<input type="text" id="h"/> <br/>
<button onclick="alert(calc()); return false;">Calculate S</button>
</form>
</body>

Categories

Resources