i am trying to make a simple calculator with javascript, but when i clicked the button '=' the result didn't appear.
<!DOCTYPE html>
<html>
<body>
<h1> Kalkulator Sederhana</h1>
<input type="text" name="angkapertama" placeholder="Angka Pertama" id="angkapertama">
<input type="text" name="angkakedua" placeholder="Angka Kedua" id="angkakedua">
<button id="hasil" onclick="tambah">=</button>
<h2 id="hsl"></h2>
<script>
var a = document.getElementById('angkapertama').value;
var b = document.getElementById('angkakedua').value;
var c = document.getElementById('hasil');
c.addEventListener('click', tambah, false);
function tambah() {
return a + b;
document.getElementById("hsl").innerHTML = tambah;
}
</script>
</body>
</html>
A number of problems with this
1) Collecting the input values from the textboxes before the user has had chance to type anything into them. You need to do that inside the event handler.
2) An inline event attribute (which was wrongly defined without the () anyway) and an eventlistener added in code. Only one is needed. The eventListener is generally considered the better way, e.g. for code maintainability and visibility.
3) Treating the values as strings and not numbers (e.g. if the code had otherwise been working, "4" + "4" would have returned "44"!)
4) returning from your tambah() function before the line which actually displayed the result. return returns from a function, it's not just for getting the result of a calculation.
This version corrects all those errors. You can run it to test it out:
var c = document.getElementById('hasil');
c.addEventListener('click', tambah, false);
function tambah() {
var a = document.getElementById('angkapertama').value;
var b = document.getElementById('angkakedua').value;
var sum = parseFloat(a) + parseFloat(b);
document.getElementById("hsl").innerHTML = sum;
}
<h1> Kalkulator Sederhana</h1>
<input type="text" name="angkapertama" placeholder="Angka Pertama" id="angkapertama">
<input type="text" name="angkakedua" placeholder="Angka Kedua" id="angkakedua">
<button id="hasil">=</button>
<h2 id="hsl"></h2>
There are a few things incorrect with your code.
When you return a + b, there's no code executed after that return statement.
I've changed the code slightly, the vars a and b are now defined inside the function, and also made sure to use parseInt on your a and b - otherwise they would end up being concatenated as strings (meaning 1 + 2 would be 12 - wrong!)
var c = document.getElementById('hasil');
c.addEventListener('click', tambah);
function tambah()
{
var a = parseInt(document.getElementById('angkapertama').value);
var b = parseInt(document.getElementById('angkakedua').value);
var result = a + b;
document.getElementById("hsl").innerHTML = result;
}
<!DOCTYPE html>
<html>
<body>
<h1> Kalkulator Sederhana</h1>
<input type="text" name="angkapertama" placeholder="Angka Pertama" id="angkapertama">
<input type="text" name="angkakedua" placeholder="Angka Kedua" id="angkakedua">
<button id="hasil">=</button>
<h2 id="hsl">answer here</h2>
</body>
</html>
A Simple example
var c = document.getElementById('hasil');
c.addEventListener('click', tambah, false);
function tambah() {
var a = document.getElementById('angkapertama').value;
var b = document.getElementById('angkakedua').value;
var sum = Number(a) + Number(b); //or
// var sum = parseFloat(a) + parseFloat(b);
document.getElementById("hsl").innerHTML = sum;
console.log(sum)
}
<h1> Kalkulator Sederhana</h1>
<input type="text" name="angkapertama" placeholder="Angka Pertama" id="angkapertama">
<input type="text" name="angkakedua" placeholder="Angka Kedua" id="angkakedua">
<button id="hasil">=</button>
<h2 id="hsl"></h2>
However, the addEventListener() function, despite it’s the standard, just doesn’t work in old browsers (Internet Explorer below version 9), and this is another big difference. If you need to support these ancient browsers, you should follow the onclick way.
HTML:
<button id="hasil" onclick="tambah()">=</button>
SCRIPT:
function tambah() {
var a = document.getElementById('angkapertama').value;
var b = document.getElementById('angkakedua').value;
var sum = Number(a) + Number(b); //or
// var sum = parseFloat(a) + parseFloat(b);
document.getElementById("hsl").innerHTML = sum;
console.log(sum)
}
content source here
Try this :
<!DOCTYPE html>
<html>
<body>
<h1> Kalkulator Sederhana</h1>
<input type="text" name="angkapertama" placeholder="Angka Pertama" id="angkapertama">
<input type="text" name="angkakedua" placeholder="Angka Kedua" id="angkakedua">
<button id="hasil" onclick="tambah()">=</button>
<h2 id="hsl"></h2>
<script>
var a = document.getElementById('angkapertama').value;
var b = document.getElementById('angkakedua').value;
var c = document.getElementById('hasil');
c.addEventListener('click', tambah, false);
function tambah() {
var sum = a + b;
document.getElementById("hsl").innerHTML = sum;
}
</script>
</body>
</html>
Related
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
Hi could anyone run this code correctly?
I learnt to make somthing similar to this
https://www.youtube.com/watch?v=vkBiEuZSq9s
but this is not a loan, it is a simple calculation
SMAL should be * 0.5
GAS * 6
CV as it is
result should be SMAL + GAS + CV
I am new to JavaScript and I need your help
Thanx
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" >
<script>
function calculate(){
var GAS = document.getElementById('GAS').value;
var SMAL = document.getElementById('SMAL').value;
var CV = document.getElementById('CV').value;
var GASAcal = (GAS * 6);
var SMALcal = (SMAL * 0.5);
var CVcal = (CV);
var total_score = CVcal + GAScal + SMALcal;
if(total_score ismap)
{
document.getElementById('total_score').innerHTML = "Total score = "+total_score;
}
}
</script>
</head>
<body dir="rtl">
<p> GAS <br><input id="GAS" type="number" min="0" max="5" step="" onchange="calculate" ></p>
<p> SMAL <br><input id="SMAL" type="number" min="0" max="100" value="1" onchange="calculate"></p>
<p> CV <br><input id="CV" type="number" min="1" max="20" value="1" onchange="calculate"></p>
<h2 id="total_score"></h2>
</body>
</html>
A couple things.
You have errors in your JavaScript. Like another person said, get familiar with your browser development tools, and using console.log() and/or alert().
You've stumbled upon an age-old issue with oninput event for Input elements. It's buggy, and depends on browser and browser version.
Anyway, without getting into too much detail (which I'm sure you can search the web for answers to), I've included a working version of your html page here. My JavaScript logic here is a poor man's version so that you can see what I did to capture the oninput events.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
var calculate;
document.addEventListener("DOMContentLoaded", function(event) {
// GAS
document.getElementById('GAS').oninput = function() {
this.onkeydown = null;
calculate.call(this);
};
document.getElementById('GAS').onkeydown = function() {
calculate.call(this);
};
// SMAL
document.getElementById('SMAL').oninput = function() {
this.onkeydown = null;
calculate.call(this);
};
document.getElementById('SMAL').onkeydown = function() {
calculate.call(this);
};
// CV
document.getElementById('CV').oninput = function() {
this.onkeydown = null;
calculate.call(this);
};
document.getElementById('CV').onkeydown = function() {
calculate.call(this);
};
calculate = function (){
//console.log("calcing...");
var GAS = document.getElementById('GAS').value;
var SMAL = document.getElementById('SMAL').value;
var CV = document.getElementById('CV').value;
var GAScal = (GAS * 6);
var SMALcal = (SMAL * 0.5);
var CVcal = (CV);
var total_score = CVcal + GAScal + SMALcal;
if(total_score)
{
//total_score = 10.620000000000001
//total_score = 10.625000000000001
document.getElementById('total_score').innerHTML = "Total score = "+ roundNumber(total_score, 2);
}
//console.log(total_score);
//console.log("calcing done");
}
// this rounds your number, and scale is to what precision we round to and return
function roundNumber(num, scale) {
if(!("" + num).includes("e")) {
return +(Math.round(num + "e+" + scale) + "e-" + scale);
} else {
var arr = ("" + num).split("e");
var sig = ""
if(+arr[1] + scale > 0) {
sig = "+";
}
return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
}
}
})
</script>
</head>
<body dir="rtl">
<p>GAS
<br>
<input id="GAS" type="number" min="0" max="5" step="" oninput="calculate">
</p>
<p>SMAL
<br>
<input id="SMAL" type="number" min="0" max="100" value="1" oninput="calculate">
</p>
<p>CV
<br>
<input id="CV" type="number" min="1" max="20" value="1" oninput="calculate">
</p>
<h2 id="total_score"></h2>
</body>
</html>
So i need to display the user id that has been generated in javascript but i have problem to display it on textbox.
here's the javascript coding:
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
}
function SaveDetails(){
var CreateuserID = generateuserID();
document.getElementById('userID').value = CreateuserID;
var name = document.getElementById('userName').value;
var occupation = document.getElementById('userOccupation').value;
sessionStorage.setItem(name, occupation);
display();
var name = document.getElementById('userName').value = "";
var occupation = document.getElementById('userOccupation').value = "";
}
function display(){
var output = document.getElementById('output');
output.innerHTML = "";
for(var i=0;i<sessionStorage.length;i++)
{
var name = sessionStorage.key(i);
var occupation = sessionStorage.getItem(name);
output.innerHTML += name+"|"+occupation+"<br>";
}
}
function generateuserID()
{
var userIDnum = 1;
userIDnum++;
}
window.addEventListener('load', AddDetails, false);
This is the HTML code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="Style.css">
<script src="script.js"></script>
</head>
<br>
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort">
<option value ="userID">userID</option>
<option value ="userID">userName</option>
<option value ="userID">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
</html>
Please help me i have been doing this for days and cant think of solution. I tried using ECMAScript and it wont work either. I'm still new and lack of knowledge.
Your generateuserID() method doesn't return anything. Even if your returned userIDnum everyone's user id will be 2. Do you realize that JavaScript just runs in the browser? None of the variables will exist between different users.
There are many mistakes in your sample. You don't need sessionStorage just for static content. Here is the working codepen [ https://codepen.io/vivekamin/pen/gQMRPx ] .I have created for you from your code. Please check it out. Here is the code. I have used createElement just for sake of working example. However, if you have many elements to append you can use createDocumentFragment which is more efficient. I am just adding the last data to HTML, output element in form of paragraph text
HTML:
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort" id ="sortBy">
<option value ="userID">userID</option>
<option value ="name">userName</option>
<option value ="occupation">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
JS Code:
let counter = 1;
let data = [];
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
let sortBy = document.getElementById('sortBy');
sortBy.addEventListener('change', SortAndDisplay, false);
document.getElementById('userID').value = counter;
}
function SortAndDisplay(){
console.log("Sorting", document.getElementById('sortBy').value);
let sortBy = document.getElementById('sortBy').value;
if(sortBy === "userID"){
data.sort(function (a, b) {
return a.id - b.id;
});
}
else{
sortByNameOrOccupation(sortBy);
}
console.log(data);
displayAfterSort();
}
function SaveDetails(){
let name = document.getElementById('userName');
let occupation = document.getElementById('userOccupation');
data.push({id: counter, name: name.value, occupation: occupation.value });
console.log(data);
counter++;
document.getElementById('userID').value = counter;
name.value='';
occupation.value ='';
let outputSection = document.getElementById('output');
let outputData = data[data.length - 1];
let newP = document.createElement('p');
newP.textContent = outputData['id'] + " " + outputData['name'] + " "+outputData['occupation'];
outputSection.appendChild(newP);
}
function sortByNameOrOccupation(attribute){
data.sort(function(a, b) {
var nameA = a[attribute].toUpperCase(); // ignore upper and lowercase
var nameB = b[attribute].toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
}
function displayAfterSort(){
let outputSection = document.getElementById('output');
outputSection.innerHTML = '';
let fragment = document.createDocumentFragment();
data.forEach(function(d) {
let p = document.createElement('p');
p.textContent = d['id'] + " " + d['name'] + " "+d['occupation'];
fragment.appendChild(p);
});
outputSection.appendChild(fragment);
}
window.addEventListener('load', AddDetails, false);
To set the value of the textbox. Do:
$('#//ID of the textbox').val(CreateuserID)
This is assuming that 'CreateuserID' is a string or int
EDIT: Your CreateuserID function will need to return a value.
This does not add the numbers instead gives NaN
<html>
<body>
<script>
function checkit()
{
x = document.getElementById("a");
x1 = parseInt(x);
y = document.getElementById("b");
y1 = parseInt(y);
alert("Answer is" + (x1 + y1));
}
</script>
<input type="text" id="a">
<input type="text" id="b">
<input type="button" onclick="checkit()">
</body>
</html>
Even tried document.getElementById("a").value;
Still gives NaN
document.getElementById returns the HTML element (an input, in your case), not its value. Try this instead:
x = document.getElementById("a").value;
I am unable to add 2 numbers taking from inputs.
<script>
x = document.getElementById('input1').value;
y = document.getElementById('input2').value;
z = Number(x)+ Number(y);
document.getElementById('submit1').addEventListener("click",alpha);
function alpha(){document.getElementById('div1').innerHTML="The answer is" + z;}
</script>
I need to do this with help of javaSCript only.
You could try something like this:
document.getElementById('submit1').addEventListener("click", function(){
// I suppose that the values you insert in your inputs are
// integers. Otherwise, you could use the parseFloat(value, 10)
// to parse float =s.
var x = parseInt(document.getElementById('input1').value);
var y = parseInt(document.getElementById('input2').value);
// Add the numbers
var z = x + y;
// Set the result in the selected div.
document.getElementById('div1').innerHTML="The answer is" + z;
});
You could try to run the following snippet:
document.getElementById('submit1').addEventListener("click", function(){
// I suppose that the values you insert in your inputs are
// integers. Otherwise, you could use the parseFloat(value, 10)
// to parse float =s.
var x = parseInt(document.getElementById('input1').value);
var y = parseInt(document.getElementById('input2').value);
// Add the numbers
var z = x + y;
// Set the result in the selected div.
document.getElementById('div1').innerHTML="The answer is " + z;
});
<input type="text" id="input1"/>
<br/>
<input type="text" id="input2"/>
<br/>
<div id="div1">
</div>
<br/>
<button id="submit1">submit</button>
You want to use parseInt() to turn a string into an int.
<html>
<head>
<title></title>
<style>
</style>
<script>
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("button").addEventListener("click",function(){
var a = parseInt(document.getElementById("input1").value);
var b = parseInt(document.getElementById("input2").value);
document.getElementById("output").innerHTML="The Answer is "+(a+b);
},false);
});
</script>
</head>
<body>
<input id="input1" type="text"/>
<input id="input2" type="text"/>
<button id="button">Add</button>
<div id="output"></div>
</body>
</html>