How to fix this function? Javascript - javascript

I'm trying to make a function that calculates the amount of gas you need by giving the distance you need to travel and your engine's consumption, however nothing happens when I click the button, here is the code:
function calc() {
var dist = document.getElementById("distance").value
var cons = document.getElementById("cons").value
var res = dist / 100 * cons
res.innerText = "You need " + res + "liters of gas.";
}
function load() {
var button = document.getElementById("button");
button.addEventListener("click", calc, false);
}
<main onload="load();">
<h2>Calculate how much gas you need</h2>
<input type="number" class="number" id="dist"><br/>
<input type="number" class="number" id="cons"><br/><br/>
<input type="button" class="button" id="button" value="Submit"><br/>
<p id="res"></p>
</main>

You can not use onload attribute with main tag.
Also, you forgot to find element #res with document.getElementById.
function calc() {
const dist = document.getElementById("dist").value;
const cons = document.getElementById("cons").value;
const res = dist / 100 * cons;
document.getElementById('res').innerText = "You need " + res + "liters of gas.";
}
function load() {
const button = document.getElementById("button");
button.addEventListener("click", calc, false);
}
<body onload="load();">
<main>
<h2>Calculate how much gas you need</h2>
<input type="number" class="number" id="dist"><br/>
<input type="number" class="number" id="cons"><br/><br/>
<input type="button" class="button" id="button" value="Submit"><br/>
<p id="res"></p>
</main>
</body>

There are several issues in your code:
You can ignore the load() by executing all your code in DOMContentLoaded.
You should refer the element p to replace the innerText property
I will also suggest you to be more careful in naming attributes.
Code Example:
<script>
document.addEventListener('DOMContentLoaded', (event) => {
function calc() {
var dist = document.getElementById("dist").value
var cons = document.getElementById("cons").value
var resEl = document.getElementById('res');
var res = dist / 100 * cons
resEl.innerText = "You need " +res+"liters of gas.";
}
var button = document.getElementById("calcButton");
button.addEventListener("click", calc);
});
</script>
<main>
<h2>Calculate how much gas you need</h2>
<input type="number" class="number" id="dist"><br/>
<input type="number" class="number" id="cons"><br/><br/>
<input type="button" class="clsButton" id="calcButton" value="Submit"><br/>
<p id="res"></p>
</main>

This happens because you put JS code on top of the actual elements!
document.getElementById("distance")
will be undefined as the distance is being rendered below that code. moreover instead of distance I see you have dist in the actual element id.
Last but not list you should put your code in script tags.
<main onload="load();">
<h2>Calculate how much gas you need</h2>
<input type="number" class="number" id="dist"><br/>
<input type="number" class="number" id="cons"><br/><br/>
<input type="button" class="button" id="button" value="Submit"><br/>
<p id="res"></p>
</main>
<script>
//we put script below html
function calc() {
var dist = document.getElementById("dist").value
var cons = document.getElementById("cons").value
var res = dist / 100 * cons
res.innerText = "You need " +res+"liters of gas.";
}
function load() {
var button = document.getElementById("button");
button.addEventListener("click", calc, false);
}
</script>

I don't know if u can do a onload on a but u can try using onclick event on the submit button instead.
<input type="button" class="button" id="button" value="Submit" onclick="calc();"><br/>
that would do the trick aswell i believe
and in your calc() function you have to find your res div :)
function calc() {
var dist = document.getElementById("distance").value
var cons = document.getElementById("cons").value
var res= document.getElementById("res")
var resAnswer = dist / 100 * cons
res.innerText = "You need " + resAnswer + "liters of gas.";
}

Related

Keeping value of search box Javascript/HTML

I made a tool which make my work a little easier by inserting a value into a url in a new window on multiple sites. It was working quite well but now I am having the problem of the search value being cleared onsubmit.
Javascript:
<script language="JAVASCRIPT">
function run() {
var request = document.text.query.value;
var req = "";
var endofurl = "endofurl.html";
for(var i = 0; i < request.length; i++) {
var ch;
if((ch = request.substring(i, i + 1)) == " ") req += " ";
else req += ch;
}
if(document.search.website.checked) {
var website = open( "https://www.website.com/" + req, "website");
}
//--></script>
HTML:
<form name="search">
Please select the networks you want to use.
<p>
</center>
</p>
<div class="row">
<div class="column">
<br>
<input name="website" type="checkbox">Website to Search
<form name="text" onsubmit="run(); return false;">
<center>And enter your Query.</center>
<center>
<input name="query" placeholder="Steropodon" value="" size="50" type="TEXT">
<input value="Search" onclick="run()" type="BUTTON">
</center>
So far, return false had been working to keep the value of the input in the form="text" input name="query" but now it seems to clear it and reload the page. I'm not sure what changed.
You have errors in your code opening and closing the tags.
Try this code. It works:
<html>
<head></head>
<body>
Please select the networks you want to use
<div class="row">
<div class="column">
<br>
<input name="website" type="checkbox">Website to Search
<form name="text" onsubmit="run(); return false;">
<center>And enter your Query.</center>
<center>
<input name="query" placeholder="Steropodon" value="" size="50" type="TEXT">
<input value="Search" onclick="run()" type="BUTTON">
</center>
</form>
</div>
</div>
<script language="JAVASCRIPT">
function run() {
var request = document.text.query.value;
var req = "";
var endofurl = "endofurl.html";
for(var i = 0; i < request.length; i++) {
var ch;
if((ch = request.substring(i, i + 1)) == " ") req += " ";
else req += ch;
}
var checkbox = document.getElementsByName("website");
if(checkbox[0].checked) {
var website = open("https://www.website.com/" + req,
"website");
}
}
</script>
</body>
</html>
Hope it helps.
I fixed it. It was not the tags. I had only pasted a small amount of the total code to make it easier to read but I failed at making it easier to read. The problem was undefined inputs. I have been adding many if statements but didn't have a corrosponding checkbox. Oops.
Thanks for the help.

JavaScript getElementById always returning null

I am trying to build a simple budget calculator, everytime I click my submit button I nothing happens. When I try to check my variable values in the console they show null, even after I have typed values in my input boxes. Can anyone tell me what I'm doing wrong? After looking through other questions on here I haven't been able to find an answer that relates to my issue.
<!DOCTYPE html>
<html>
<head>
<title>Budget Calculator</title>
<style>
input {display:block;}
#clear {float:left;}
#submit {float:left;}
</style>
<script type="text/javascript">
var kms = document.getElementById("kmTravelled");
var rent = document.getElementById("rentPerMonth");
var carCost = document.getElementById("carPayment");
var costPerTrip = (kms/12.75)*20;
var total = Math.round((costPerTrip + rent + carCost)*100)/100;
function calculate()
{
document.getElementById("calculator").innerHTML = total;
}
</script>
</head>
<body>
<form id="myForm")>
Km travelled per day: <input type="number" name="kmTravelled" />
Rent per month: <input type="number" name="rentPerMonth" />
Car payment per month: <input type="number" name="carPayment" />
</form>
<button id="submit" type="button" onclick="calculate();">
Submit
</button>
<button id="clear" type="clear">
Clear
</button>
<p id = "calculator">
</p>
<script>
calculate();
</script>
</body>
I suggest to use id attributes and move the parts for getting the values inside of the function, as well as getting value property and cast the string value to number for calculation.
function calculate() {
var kms = +document.getElementById("kmTravelled").value;
var rent = +document.getElementById("rentPerMonth").value;
var carCost = +document.getElementById("carPayment").value;
var costPerTrip = (kms / 12.75) * 20;
var total = Math.round((costPerTrip + rent + carCost) * 100) / 100;
document.getElementById("calculator").innerHTML = total;
}
input { display: block; }
#clear { float: left; }
#submit { float: left; }
<form id="myForm">
Km travelled per day: <input type="number" name="kmTravelled" id="kmTravelled"/> Rent per month: <input type="number" name="rentPerMonth" id="rentPerMonth" /> Car payment per month: <input type="number" name="carPayment" id="carPayment" />
</form>
<button id="submit" type="button" onclick="calculate();">Submit</button>
<button id="clear" type="clear">Clear</button>
<p id="calculator"></p>
You don't have no id's in you input's but you have name's instead so you could use name selector $('[name=""]') like :
var kms = document.querySelector("[name='kmTravelled']").value;
var rent = document.querySelector("[name='rentPerMonth']").value;
var carCost = document.querySelector("[name='carPayment']").value;
If you want really to use id's , just add them and the JS code could be :
var kms = document.querySelector("#kmTravelled").value;
var rent = document.querySelector("#rentPerMonth").value;
var carCost = document.querySelector("#carPayment").value;
NOTE : You should get just the value of the element not the whole object.
Hope this helps.
var kms = document.querySelector("[name='kmTravelled']").value;
var rent = document.querySelector("[name='rentPerMonth']").value;
var carCost = document.querySelector("[name='carPayment']").value;
var costPerTrip = (kms/12.75)*20;
var total = Math.round((costPerTrip + rent + carCost)*100)/100;
function calculate()
{
document.getElementById("calculator").innerHTML = total;
}
calculate();
input {
display:block;
}
#clear {
float:left;
}
#submit {
float:left;
}
<form id="myForm")>
Km travelled per day: <input type="number" name="kmTravelled" />
Rent per month: <input type="number" name="rentPerMonth" />
Car payment per month: <input type="number" name="carPayment" />
</form>
<button id="submit" type="button" onclick="calculate();">
Submit
</button>
<button id="clear" type="clear">
Clear
</button>
<p id = "calculator"></p>
I think you need to try getElementById('kmTravelled').
First, you have to give proper id in HTML tag. check your HTML tag, convert those name into id.
Now you have to slightly change your javascript code, if you look at your code you didn't assign any value to your variable. fix these problems and your code will run properly.

cloneNode and total the value of all nodes (parent+childs). Javascript

I want to total the values of all input, but in the beginning there's only one input element and you add the clone(s) with a button. Actually I have two issues:
1. How to place the clone node always under the node before it.
2. How to total the values of all nodes.
Here's the code:
function nambahData() {
var a = document.getElementById("harga");
var b = a.cloneNode(false);
document.getElementById("form").appendChild(b);
}
function ditotal() {
var x = document.getElementById("harga").value;
var y = document.getElementById("harga").childNode.value;
document.getElementById("total").value = parseInt(x) + parseInt(y);
}
</script>
<div id="form">
<input id="harga" type=number>
<br>
</div>
<button onclick="nambahData()">add data</button>
<br>
<button onclick="ditotal()">total all</button>
<input id="total" type=number>
Hope this helps you ..
window.nambahData = function() {
var a = document.getElementsByName("harga");
var b = a[0].cloneNode(false);
document.getElementById("form").appendChild(b);
}
window.ditotal = function() {
var totalItems = 0;
for(i=document.getElementsByName("harga").length-1;i>=0;i--)
{
var item = document.getElementsByName("harga")[i];
totalItems += parseFloat(item.value);
}
document.getElementById("total").value = totalItems;
}
.inputStyle{
display:block;
}
<div id="form">
<input name="harga" type="number" class="inputStyle">
</div>
<button onclick="nambahData()">add data</button>
<br>
<button onclick="ditotal()">total all</button>
<input id="total" type=number>

Trying to get the result of javascript function using innerHTML

I have a simple program that takes in an input and then should show that input multiplied up to 100. I am new to this, but have tried to get it to work before posting here. I have the link to the program that I am referring to.
I want the result to be shown, but I cannot figure out why it is not showing.
You can see what I have below. I think I do not have the html and javascript hooked up properly.
Here is my html:
<body>
<input type="number" id="NumToBMultiplied" class="value" placeholder="Enter an integer" />
<input type='submit' id='RunProg' class='button' />
<p> id='result'</p>
</body>
Here is my Javascript:
h = document.getElementByID('NumToBMultiplied');
var result = document.getElementbyID('RunProg').addEventListener('click', function () {
for (i = 0; i < 100; i++)
return i * h;
}
});
document.getElementByID('result').innerHTML = result;
http://jsbin.com/wayejequxu/1/edit?html,js,output
Any help is appreciated!
From how I understand your code, you are wanting to multiply the input 100 times, then output that into a HTML tag. The result in your example is not being added to the result paragraph as it isn't in the loop.
HTML
This is changed only slightly. Notice the onClick="solve()" to the button instead of adding an event listener.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<input type="number" id="NumToBMultiplied" class="value" placeholder="Enter an integer"/>
<input type="submit" id="RunProg" onClick="solve()" class="button"/>
<p id="result"> </p>
</body>
</html>
Javascript
I've added a line break after each result of the for loop so the result is easier to read. And the output is cleared before a new solve() is run.
var output = document.getElementById("result");
function solve() {
var input = document.getElementById("NumToBMultiplied").value;
output.innerHTML = "";
for(i=0; i < 100; i++) {
output.innerHTML += i * input + "<br/>";
}
}
Result here: http://jsbin.com/foduyofewi/1/
You need to store your result in variable inside a callback and set innerHTML also in callback:
document.getElementById('RunProg').addEventListener("click", function() {
var result = 1;
var input = +h.value;
for (var i = 1; i < 100; i++) {
result *= i * input;
}
document.getElementById("result").innerHTML = result;
});
DEMO
Pure Javascript version:
function multiply(x) {
var result = document.getElementById('result');
result.innerHTML = x.value * 100;
}
<input type="number" id="NumToBMultiplied" class="value" onchange="multiply(this)" placeholder="Enter an integer"/>
<p id="result"></p>
This is the jQuery version:
$(document).ready(function() {
$('#NumToBMultiplied').on('change',function(){
$('#result').text($(this).val()*100);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="NumToBMultiplied" class="value" placeholder="Enter an integer"/>
<p id="result"></p>
Just some modification to your code to remove some of the typos and errors. I'm not sure you can return the result like how you have done it, a more traditional approach is shown below.
Full code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="number" id="NumToBMultiplied" class="value" placeholder="Enter an integer" />
<input type='submit' id='RunProg' class='button' />
<p id='result'> </p>
</body>
<script>
h = document.getElementById('NumToBMultiplied').value;
document.getElementById('RunProg').addEventListener('click', function () {
for (i = 0; i < 100; i++){
var result = h*i;
}
document.getElementById('result').innerHTML = result;
});
</script>
</html>

Dynamic Javascript Div

Got JS Fiddle to work
http://jsfiddle.net/pskjxofo/
Attached I have the following function, the purpose of which is to perform basic calculation. I also added a feature for adding more boxes for calculation. What I am currently stuck on is how to tell Javascript to make dynamic divs, and how to tell it to perform the same calculations for each line every time I click on Calculate. Assistance on this would be greatly appreciated. Thank you all in advance.
<div id="redo">
2 X
<input type="text" id="initial">
= <input type="text" id="solved">
<input type="submit" value="Calculate" onclick="calculait()">
<input type="submit" value="Add Another Box" onclick="addmore()">
</div>
<div id="main"></div>
<script type="text/javascript">
function calculait(){
var first = document.getElementById('initial');
var second = document.getElementById('solved');
second.value = first.value * 2;
}
function addmore(){
var bar = document.getElementById('main');
bar.innerHTML = bar.innerHTML + "<div id='redo'>2 X
<input type='text' id='initial'> = <input type='text' id='solved'>
<input type='submit' value='Calculate' onclick='calculait()'
<input type='submit' value='Add Another Box' onclick='addmore()";
}
</script>
Here is one of the many ways to do it. You could have this HTML structure:
<div id="main">
<div class="operation">
2 X <input type="text" class="initial"/>=
<input type="text" class="solved"/>
</div>
</div>
<input type="submit" value="Calculate" onclick="calculait()"/>
<input type="submit" value="Add Another Box" onclick="addmore()"/>
And this JS:
// Main container for all operations
var main = document.getElementById('main');
// Piece of HTML you'll be duplicating
var op = document.getElementsByClassName('operation')[0].outerHTML;
function calculait() {
// Get every operation div
var operations = document.getElementsByClassName('operation');
// For each of them, calculate
for(var i=0, l=operations.length; i<l; i++){
operations[i].getElementsByClassName('solved')[0].value =
parseFloat(operations[i].getElementsByClassName('initial')[0].value) * 2;
}
}
function addmore() {
main.insertAdjacentHTML('beforeend',op);
}
JS Fiddle Demo
If I understood correctly, I think this code will help.
First of all, change your ids for classes (IDs must be always unique in the page).
<input type="text" class="initial">
<input type="text" class="solved">
And in the JS, you use a for to iterate for this elements.
function calculait() {
var initial = document.getElementsByClassName('initial');
var solved = document.getElementsByClassName('solved');
for (var i = 0; i < initial.length; i++) {
solved[i].value = initial[i].value * 2;
}
}
function addmore() {
var bar = document.getElementById('main');
var html = "<div>2 X ";
html += "<input type='text' class='initial'> = ";
html += "<input type='text' class='solved'>";
html += "</div>";
bar.innerHTML = bar.innerHTML + html;
}
JSFiddle: http://jsfiddle.net/pskjxofo/2/
Give it a try and let me know if it helps!
When you write JavaScript use a debugger, your code didn't parse. You can find one in your browser by hitting F12.
Don't repeat yourself. A clean solution is to put html to duplicate into a template or similar and call a function to copy it.
Use input type=number for numbers.
<html>
<meta charset="utf-8">
<template id="calculate_template">
<form id="" class="calculate_form">
<input value="2" type="number" name="initial_1"> X
<input type="number" name="initial_2"> =
<input type="number" name="solved" disabled="disabled" >
</form>
</template>
<div id="main">
<button onclick="addmore();">Add Another Box</button>
<button onclick="calculate();">Calculate</button>
</div>
<script type="text/javascript">
function calculate(){
/*Calculates all*/
var forms = document.getElementsByClassName('calculate_form'),
i,
length = forms.length;
for(i = 0; i < length; i++){
console.log(forms[i]);
forms[i]['solved'].value = forms[i]['initial_1'].value * forms[i]['initial_2'].value;
}
}
function addmore(){
var main = document.getElementById('main');
main.insertAdjacentHTML("beforeend", document.getElementById('calculate_template').innerHTML);
}
addmore();
</script>
</html>
Demonstration
Here's a way of doing it:
var counter = 0;
function calculait(calculationId) {
var first = document.getElementById('initial' + calculationId);
var second = document.getElementById('solved' + calculationId);
second.value = first.value * 2;
}
function addmore() {
counter++;
var bar = document.getElementById('main');
var newDiv = document.createElement("div");
newDiv.id = "redo" + counter;
newDiv.innerHTML = "2 X <input type='text' id='initial" + counter + "'/> = <input type='text' id='solved" + counter + "'/><input type='submit' value='Calculate' onclick='calculait(" + counter + ")'/><input type='submit' value='Add Another Box' onclick='addmore(" + counter + ")'/>";
bar.appendChild(newDiv);
}
<div id="main"><div id="redo0">2 X <input type="text" id="initial0" /> = <input type="text" id="solved0" /><input type="button" value="Calculate" onclick="calculait(0)" /><input type="button" value="Add Another Box" onclick="addmore(0)" /></div>
</div>
HTML
<p id="operations"></p>
<p>
<input type="submit" value="Calculate" onclick="calc()" />
<input type="submit" value="Add operation" onclick="addOp()" />
</p>
Javascript
var id = 0, multiplier = 2;
var operations = document.getElementById('operations');
function addOp() {
++id;
var p = document.createElement("p");
var right = document.createElement("input");
right.id = 'right_' + id;
right.type = 'text';
var result = document.createElement('input');
result.id = 'result_' + id;
right.type = 'text';
p.innerHTML = multiplier + ' x ';
p.appendChild(right);
p.innerHTML += ' = ';
p.appendChild(result);
operations.appendChild(p);
}
function calc() {
for(var i = 1; i <= id; i++) {
var right = document.getElementById('right_' + i);
var result = document.getElementById('result_' + i);
result.value = multiplier * right.value;
}
}
addOp();
JSFiddle : http://jsfiddle.net/0Lcg0pyz/

Categories

Resources