Getting value from textbox with javascript - javascript

Here is my code. No idea why it is not working need help inspecting my code.
I'm trying to calculate the average and sum from the value input by the user. The html works well but my javascript code is somehow wrong. Help please
< script >
function calc() {
int a = parseInt(document.getElementsByName("english").value);
int b = parseInt(document.getElementsByName("bmelayu").value);
int c = parseInt(document.getElementsByName("math").value);
int d = parseInt(document.getElementsByName("geo").value);
int e = parseInt(document.getElementsByName("hist").value);
int sum = a + b + c + d + e;
int average = (a + b + c + d + e) / 5;
document.getElementById("sum").innerHTML = sum;
document.getElementById("average").innerHTML = average;
} < /script>
<html>
<head>
<title>Assignment3</title>
</head>
<script>
function calc() {
int a = parseInt(document.getElementsByName("english").value);
int b = parseInt(document.getElementsByName("bmelayu").value);
int c = parseInt(document.getElementsByName("math").value);
int d = parseInt(document.getElementsByName("geo").value);
int e = parseInt(document.getElementsByName("hist").value);
int sum = a + b + c + d + e;
int average = (a + b + c + d + e) / 5;
document.getElementById("sum").innerHTML = sum;
document.getElementById("average").innerHTML = average;
}
</script>
<body>
<form name="form1">
English :
<input type="number" name="english">
<br>Bahasa Melayu :
<input type="number" name="bmelayu">
<br>Math :
<input type="number" name="math">
<br>Geography :
<input type="number" name="geo">
<br>History :
<input type="number" name="hist">
<br>
<button onclick="calc()">Calculate</button>
</form>
<p id="sum"></p>
<p id="average"></p>
</body>
</html>

function calc() {
var a = parseInt(document.getElementById("english").value);
var b = parseInt(document.getElementById("bmelayu").value);
var c = parseInt(document.getElementById("math").value);
var d = parseInt(document.getElementById("geo").value);
var e = parseInt(document.getElementById("hist").value);
console.log(a);
var sum = a + b + c + d + e;
var average = (a + b + c + d + e) / 5;
document.getElementById("sum").innerHTML = sum;
document.getElementById("average").innerHTML = average;
}
<html>
<head>
<title>Assignment3</title>
</head>
<body>
English :
<input type="number" id="english">
<br>Bahasa Melayu :
<input type="number" id="bmelayu">
<br>Math :
<input type="number" id="math">
<br>Geography :
<input type="number" id="geo">
<br>History :
<input type="number" id="hist">
<br>
<button onclick="calc();">Calculate</button>
<p id="sum"></p>
<p id="average"></p>
</body>
</html>

function calc() {
var a = parseInt(document.getElementsByName("english")[0].value);
var b = parseInt(document.getElementsByName("bmelayu")[0].value);
var c = parseInt(document.getElementsByName("math")[0].value);
var d = parseInt(document.getElementsByName("geo")[0].value);
var e = parseInt(document.getElementsByName("hist")[0].value);
var sum = a + b + c + d + e;
var average = (a + b + c + d + e) / 5;
document.getElementById("sum").innerHTML = sum;
document.getElementById("average").innerHTML = average;
}

Hey I'm glad you found your answer, but I thought it might help you out if you see a different approach:
function calc() {
var elements = Array.prototype.slice.call(document.querySelectorAll(".grade-val"));
var grades = elements.map(function(element) {
return element.value;
});
var sum = grades.reduce(function(s, c) {
return parseInt(s, 10) + parseInt(c, 10);
});
var average = sum / grades.length;
document.getElementById("sum").innerHTML = sum;
document.getElementById("average").innerHTML = average;
}
<html>
<head>
<title>Assignment3</title>
</head>
<body>
English :
<input type="number" class="grade-val" name="english">
<br>Bahasa Melayu :
<input type="number" class="grade-val" name="bmelayu">
<br>Math :
<input type="number" class="grade-val" name="math">
<br>Geography :
<input type="number" class="grade-val" name="geo">
<br>History :
<input type="number" class="grade-val" name="hist">
<br>
<button onclick="calc();">Calculate</button>
<p id="sum"></p>
<p id="average"></p>
</body>
</html>
Note that I've added a class grade-val on each of the elements, if you simply want to add another subject to be taken into consideration you don't have to modify the code but only the markup (insert new element with the same class). Simple as that.
This is going to work on IE8+

I have fixed your snippet - you have made a number of errors there. Now it works
function calc() {
var a = parseInt(document.getElementsByName("english")[0].value);
var b = parseInt(document.getElementsByName("bmelayu")[0].value);
var c = parseInt(document.getElementsByName("math")[0].value);
var d = parseInt(document.getElementsByName("geo")[0].value);
var e = parseInt(document.getElementsByName("hist")[0].value);
var sum = a + b + c + d + e;
var average = (a + b + c + d + e) / 5;
document.getElementById("sum").innerHTML = sum;
document.getElementById("average").innerHTML = average;
}
<html>
<head>
<title>Assignment3</title>
</head>
<script>
function calc() {
int a = parseInt(document.getElementsByName("english")[0].value);
int b = parseInt(document.getElementsByName("bmelayu")[0].value);
int c = parseInt(document.getElementsByName("math")[0].value);
int d = parseInt(document.getElementsByName("geo")[0].value);
int e = parseInt(document.getElementsByName("hist")[0].value);
int sum = a + b + c + d + e;
int average = (a + b + c + d + e) / 5;
document.getElementById("sum").innerHTML = sum;
document.getElementById("average").innerHTML = average;
}
</script>
<body>
<form name="form1">
English :
<input type="number" name="english">
<br>Bahasa Melayu :
<input type="number" name="bmelayu">
<br>Math :
<input type="number" name="math">
<br>Geography :
<input type="number" name="geo">
<br>History :
<input type="number" name="hist">
<br>
<button onclick="calc()">Calculate</button>
</form>
<p id="sum"></p>
<p id="average"></p>
</body>
</html>

Related

Why won't nothing show. Did I mess up my if statement?

So I have this script that get 2 prices, and then finds the sum of it, and then finds a percentage of the sum depending on what state you choose, and then it adds the percentage. This script worked kind of fine without the if..else statement, but now that I added it, it won't work. Please help. Script:
<!DOCTYPE html>
<html>
<head>
<title>Test!!!!!</title>
<style>
</style>
</head>
<body>
<h2> Price checker </h2>
<input id = "x" type = "number" placeholder = "Price 1" >
<br><br><br>
<input id = "y" type = "number" placeholder = "Price 2" >
<br><br><br>
<select id="s">
<option value="NJ">NJ</option>
<option value="NY">NY</option>
<option value="PA">PA</option>
<option value="FL">FL</option>
</select>
<br><br><br>
<button onclick = "theFunction()">Calculate price</button>
<p id = "d"></p>
<script>
function theFunction() {
var x = document.getElementById("x").value
var y = document.getElementById("y").value
var z = +x + +y
var v = document.getElementById("s").value
var percentToGet;
var percent;
var final;
if v == "NJ" {
var percentToGet = 6.625;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
} else if v == "NY" {
var percentToGet = 4;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
}else if v == "PA" {
var percentToGet = 2;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
} else if v == "FL" {
var percentToGet = 6;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
}
document.getElementById("d").innerHTML = z + " " + final
}
</script>
</body>
</html>
Your if statement in the script tag ,is javascript code which is not having the parentheses.
It will be => if (v == "NJ") { }
Refer this MDN Web Docs to learn more if...else

How can I grab an HTML slider value as an integer for JavaScript?

I'm trying to obtain a value out of an HTML slider so I can dynamically use it as an integer in JavaScript.The problem I'm having is I can't seem to use the value as a proper integer.
For example, if my slider value was 5 & if l tried to store it in a variable and add 10, it would output as '510' instead.
Maybe I'm an idiot and missing something very fundamental or simple, but it always ends up as a string in the end.I have tried parseInt() as well, but it doesn't seem to help.
I've set up a simple example of code below:
JS
var sliderUnit = document.getElementById("slider");
var outputUnit = document.getElementById("amtOutput");
var a = 0;
var b = 10;
outputUnit.innerHTML = sliderUnit.value;
sliderUnit.oninput = function(){
outputUnit.innerHTML = this.value;
console.log(sliderUnit.value);
a = this.value;
parseInt(a);
}
function test(){
b += a;
console.log("b: " + b + " | a: " + a);
}
HTML
<div class="sliderContainer">
<input type="range" min="1" max="15" value="7" id="slider">
<input type="submit" value="Submit" onclick="test()" />
| Slider number: <span id="amtOutput"></span>
</div>
The problem is that your are calling the parseInt(a) but the returned Integer value is not being handled properly, you should do as this a = parseInt(a);
var sliderUnit = document.getElementById("slider");
var outputUnit = document.getElementById("amtOutput");
var a = 0;
var b = 10;
outputUnit.innerHTML = sliderUnit.value;
sliderUnit.oninput = function(){
outputUnit.innerHTML = this.value;
console.log(sliderUnit.value);
a = this.value;
a = parseInt(a); // Change this line
}
function test(){
b += a;
console.log("b: " + b + " | a: " + a);
}
<div class="sliderContainer">
<input type="range" min="1" max="15" value="7" id="slider">
<input type="submit" value="Submit" onclick="test()" />
| Slider number: <span id="amtOutput"></span>
</div>
If not the variable a will continue to be a string becouse it wasn't changed
You need to parse the string as int using parseInt.
Working code:
var sliderUnit = document.getElementById("slider");
var outputUnit = document.getElementById("amtOutput");
var a = 0;
var b = 10;
outputUnit.innerHTML = sliderUnit.value;
sliderUnit.oninput = function(){
outputUnit.innerHTML = this.value;
console.log(sliderUnit.value);
a = this.value;
parseInt(a);
}
function test(){
b = parseInt(b)
a = parseInt(a);
b += a;
console.log("b: " + b + " | a: " + a);
}
<div class="sliderContainer">
<input type="range" min="1" max="15" value="7" id="slider">
<input type="submit" value="Submit" onclick="test()" />
| Slider number: <span id="amtOutput"></span>
</div>
Working JSFiddle

JavaScript calculator not updating values

I have a problem with my JavaScript calculator. Whenever I want to add, for example, 5+5, the result stays at 10 (blocked on one value) and does not add to the previous result (10, 15, 20, etc.).
Here is my code:
function add() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a + b);
document.getElementById('result').value = +c;
}
function sub() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a - b);
document.getElementById('result').value = +c;
}
function mult() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a * b);
document.getElementById('result').value = +c;
}
function div() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a / b);
document.getElementById('result').value = +c;
}
function divmod() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a % b);
document.getElementById('result').value = +c;
}
<form name="calculator">
<input type="text" id="l1" />
<input type="text" id="l2" />
<br/>
<input type="button" value="+" onclick="add()" />
<br/>
<input type="button" value="-" onclick="sub()" />
<br/>
<input type="button" onclick="mult()" />
<br/>
<input type="button" value="%" onclick="divmod()" />
<input type="button" value="/" onclick="div()" />
<br/>
<input type="button" value="clean" class="class2" />
<br/>
<p style="color:white; font-size:30px;">Result:</p>
<input type="text" id="result" />
<br/>
</form>
Where is the problem? I tried add + before = in document.getElementById('result').value = +c but it did not update the value then, but added 5 + 5 as 55.
While the +c is on the right track (converting c to a number), c is already a number, it is the result of parseInt(). The reason you got 55 is because it was concatenating strings, not adding numbers (JS can be funky with the string to number thing because it is not a strongly typed language). Javascript's type coercion can be a big pain sometimes!
I believe that getting the value of result, casting it to an integer, adding c to that integer, and THEN setting the DOM element value will get you the behavior you are looking for.
I am being intentionally vague because I believe you have demonstrated that you have the knowledge and tools to do this from your code sampling above. If you still can't get it to work after more effort, please comment on this answer and I will provide a more in depth solution.
You need to add to the number by first parsing the value to an int:
document.getElementById('result').value = parseInt(document.getElementById('result').value) + c;
With just a = newValue, that is changing the value of result to be the c variable .
With just a += newValue, that is concatenation since document.thing.value will always return a string, and a string + number promotes the number to a string.
So you need to say oldStringValue = parseInt(oldStringValue) + newNumberValue;
The value of result also needs to be initialized to 0, either through the HTML or JavaScript, otherwise parseInt() will return NaN. I chose to do it in the JavaScript, as that's more clear.
document.getElementById('result').value = 0;
function add() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a + b);
document.getElementById('result').value = parseInt(document.getElementById('result').value) + c;
}
function sub() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a - b);
document.getElementById('result').value = parseInt(document.getElementById('result').value) + c;
}
function mult() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a * b);
document.getElementById('result').value = parseInt(document.getElementById('result').value) + c;
}
function div() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a / b);
document.getElementById('result').value = parseInt(document.getElementById('result').value) + c;
}
function divmod() {
var a = parseInt(document.getElementById('l1').value);
var b = parseInt(document.getElementById('l2').value);
var c = parseInt(a % b);
document.getElementById('result').value = parseInt(document.getElementById('result').value) + c;
}
<form name="calculator">
<input type="text" id="l1" />
<input type="text" id="l2" />
<br/>
<input type="button" value="+" onclick="add()" />
<br/>
<input type="button" value="-" onclick="sub()" />
<br/>
<input type="button" onclick="mult()" />
<br/>
<input type="button" value="%" onclick="divmod()" />
<input type="button" value="/" onclick="div()" />
<br/>
<input type="button" value="clean" class="class2" />
<br/>
<p style="color:white; font-size:30px;">Result:</p>
<input type="text" id="result" />
<br/>
</form>

How Resolve Currency IDR in javascript

How can resolve script like this ?
for example count or minus Variable A and Variable B in currency IDR
thanks, anyone can help me ...
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
</head>
<body>
<form name="form1">
<input id="harga" onkeyup="formatangka_titik()" type="text" />
<input id="diskon" onkeyup="formatangka_titik()" type="text" />
<input id="bayar" onkeyup="formatangka_titik()" type="text" />
</form>
</body>
</html>
here code javascript function :
<script type="text/javascript">
function formatangka_titik()
{
a = form1.harga.value;
b = a.replace(/[^\d]/g,"");
c = "";
panjang = b.length;
j = 0;
for (i = panjang; i > 0; i--)
{
j = j + 1;
if (((j % 3) == 1) && (j != 1))
{
c = b.substr(i-1,1) + "." + c;
} else {
c = b.substr(i-1,1) + c;
}
}
form1.harga.value = c;
</script>
I think your problem is that you are adding two strings together, which will concatenate the strings instead of add the numeric values.
Example adding string types:
var a = '1';
var b = '2';
console.log(a + b); // prints '12' to the console
Example adding int types:
var a = 1;
var b = 2;
console.log(a + b); // prints '3' to the console
JavaScript is loosely typed, so it's not always immediately apparent what a variable's type is.
You can do a few things to change a string-type variable to an int.
Here are a couple common ways:
var stringNum = '123';
var intNum1 = parseInt(stringNum, 10);
var intNum2 = +stringNum;
Specifically, your code would need to look something like this:
function formatangka_titik() {
var a = form1.harga.value.replace(/[^\d]/g, "");
var b = form1.diskon.value.replace(/[^\d]/g, "");
var a = +a; // converts 'a' from a string to an int
var b = +b; // converts 'b' from a string to an int
form1.harga.value = formatNum(a);
form1.diskon.value = formatNum(b);
form1.bayar.value = formatNum(+a + b);
}
function formatNum(rawNum) {
rawNum = "" + rawNum; // converts the given number back to a string
var retNum = "";
var j = 0;
for (var i = rawNum.length; i > 0; i--) {
j++;
if (((j % 3) == 1) && (j != 1))
retNum = rawNum.substr(i - 1, 1) + "." + retNum;
else
retNum = rawNum.substr(i - 1, 1) + retNum;
}
return retNum;
}
<form name="form1">
<input id="harga" onkeyup="formatangka_titik()" type="text" />
<input id="diskon" onkeyup="formatangka_titik()" type="text" />
<input id="bayar" onkeyup="formatangka_titik()" type="text" />
</form>
In above example how we can calculate percentage for IDR currency.

The functions aren't cooperating :/

function myFunction() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoX").innerHTML = x;
var y = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoY").innerHTML = y;
document.getElementById("demoP").innerHTML = " + ";
document.getElementById("equal").innerHTML = " = ";
document.getElementById("input").innerHTML = "<input id=>";
document.getElementById("check").innerHTML = "<button>Check</button>";
}
function myBunction() {
myFunction();
var b, text;
// Get the value of the input field with id="numb"
b = document.getElementById("input").value;
var D = document.getElementById("demoX").value;
var E = document.getElementById("demoY").value;
// If x is Not a Number or less than one or greater than 10
if (b == E + D) {
text = "Input is ok";
} else {
text = "Input not valid";
}
document.getElementById("demo").innerHTML = text;
}
<p>Click the button to display a random number between 1 and 10.</p>
<button onclick="myFunction()">Try it</button>
<br> <br>
<span id="demoX"></span>
<span id="demoP"></span>
<span id="demoY"></span>
<span id=equal></span>
<span id=input></span>
<span onclick="myBunction()" id=check></span>
<p id="demo"></p>
The first function throws two random numbers and the second one should check if the input form person is correct but "document.getElementById("demoX").value" returns nothing ... I was trying check values with console.log but it returns like nothing is define.
I was just trying to merge two functions from w3schools but it took me so much time. :/
Your problem is four-fold. One:
document.getElementById("demoX").value
does not return anything. A <span> element has no value. It has an innerHTML, just what you used to set it.
Two:
if (b == E + D) {
E and D will be strings. The result of adding two strings is a combined string.
"4" + "3" is not "7", it is "43".
You want to convert them to numbers first. Among other things, an unary + can do that. Try:
b = +b;
D = +D;
E = +E;
if (b == E + D) {
Three: You want to reset the form after you read out all values, not before.
Four: What's all that business creating all those fixed input fields and buttons dynamically via innerHTML anyway? Just put them into the HTML directly and let them sit there.
So...
function reset() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoX").innerHTML = x;
var y = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoY").innerHTML = y;
document.getElementById("input").value = "";
document.getElementById("demoP").innerHTML = " + ";
document.getElementById("equal").innerHTML = " = ";
}
function check() {
var b, D, E, text;
// Get the value of the input field with id="numb"
b = +document.getElementById("input").value;
D = +document.getElementById("demoX").innerHTML;
E = +document.getElementById("demoY").innerHTML;
if (b == E + D) {
text = "Input is ok";
} else {
text = "Input not valid";
}
document.getElementById("demo").innerHTML = text;
reset();
}
reset();
<p>Click the button to display a random number between 1 and 10.</p>
<span id="demoX"></span>
<span id="demoP"></span>
<span id="demoY"></span>
<span id="equal"></span>
<input id="input">
<button onclick="check()">Check</button>
<p id="demo"></p>
Solved and nicer code.
Test
<script>
//=====|Generate the problem|=====//
function myGenerator() {
var x = Math.floor((Math.random() * 100) + 1);
document.getElementById("demoX").innerHTML = x;
var y = Math.floor((Math.random() * 100) + 1);
document.getElementById("demoY").innerHTML = y;
document.getElementById("demoP").innerHTML = " + ";
document.getElementById("equal").innerHTML = " = ";
document.getElementById("numbs").innerHTML = "<input id=numb>";
document.getElementById("check").innerHTML = "<button>Check</button>";
}
//=====|Check the given solution|=====//
function myChecker() {
var a, text;
a = document.getElementById("numb").value;
var b = parseFloat(document.getElementById("demoX").textContent);
var c = parseFloat(document.getElementById("demoY").textContent);
//=====|Simple if|=====//
if (a == b + c) {
alert("Congratulation");
text = "Right";
} else {
alert("Maybe next time");
text = "Wrong";
}
document.getElementById("demo").innerHTML = text;
//=====|Just for control|=====//
console.log(a);
console.log(b);
console.log(c);
}
</script>
<h1>Click to start</h1>
<button onclick="myGenerator()">Try it</button>
<br>
<br>
<!--=====|Hidden Stuff|=====//-->
<span id="demoX"></span>
<span id="demoP"></span>
<span id="demoY"></span>
<span id="equal"></span>
<span onclick="myChecker()" id=check></span>
<span id="numbs"></span>
<!--=====|Response|=====//-->
<p id="demo">

Categories

Resources