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.
Related
I'm trying to create a list based off of 2 input fields. The first input will be a name and the second an integer.
What I'm trying to achieve is having the name displayed multiplied by the amount of the input integer. I have got the name to display based off the input, but have been unable to have it displayed multiple times based on the input integer.
Here's an example image of what I'm looking to achieve
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
Fiddle: https://jsfiddle.net/grnct2yz/
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="number" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
for(let i = 0; i < document.getElementById("count").value; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
I have added a loop and changed the input type to number so we are sure that it's going to insert a number in the loop. Is this what you wanted?
What the code I added does is cycling a number of times equal to the number inputted and then executing the code you wrote.
for loops work this way:
you set an initial statement that is executed at the beginning of the loop, only once (let i = 0 sets a new iterable variable i),
then you set a condition that is checked before every iteration of the loop to make it run (i < document.getElementById("count").value checks that it executes up to and not more than X times, where X is the number inputted),
then you set an operation to be executed at the end of each loop (i++ increments the value of i by one).
Here is another way of doing it:
const name=document.getElementById("name"),
count=document.getElementById("count"),
list=document.getElementById("list");
document.getElementById("add").onclick = function() {
list.insertAdjacentHTML("beforeend",[...Array(+count.value)].map(s=>`<div>${name.value}</div>`).join(""))
name.value = ""; // clear the value
}
<input type="text" value="Michael" id="name" /><br>
<input type="text" value="5" id="count" /><br>
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
Just your Improved code based on your needs we can achieve this in many ways.
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var count = document.getElementById("count").value;
if (parseInt(count) != 'NaN') {
var list = document.getElementById("list");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
count = parseInt(count);
for (var i = 0; i < count; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
}
}
</script>
</body>
</html>
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.";
}
I'm trying to use the information that I obtain through a form via a submit button, do a little processing, and print it out onto the web page, preventing it from being submitted to a web server by including (return false).
Here is the code to the page:
<html>
<head>
<title>SmithSellsStuff</title>
</head>
<body>
I'm too cheap to buy something nice
<script>
var myData = {
price: "4.25",
taxRate: "0.07",
shipRate: "0.02"
};
myData.calculateTotal = function() {
myData.name = document.getElementById("name");
myData.date = document.getElementById("date");
myData.numItems = document.getElementById("number of items");
var itemTotal = myData.numItems * myData.price;
var taxTotal = (myData.numItems * myData.price) * myData.taxRate;
var shipTotal = (myData.numItems * myData.price) * myData.shipRate;
document.writeln(itemTotal);
document.writeln(taxTotal);
document.writeln(shipTotal);
};
</script>
<form>
</p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
</p>
<label>Number of items: <input type="number" name="number of items" id="number of items" tabindex="3"/></label>
</p>
<input type="submit" onclick="calculateTotal(); return false;"/>
</form>
</body>
</html>
On the first page, I have a simple form with a field for name, date, number of items total, and a submit button. One error I'm getting is in the onclick tag. It says '_kof_1' is defined but never used. I don't think it is allowing my calculateTotal function to call.
It's because the function was not declared in the global scope, but rather as a property of myData.
myData.calculateTotal = function() {
To solve this, simply change the call to:
<input type="submit" onclick="myData.calculateTotal(); return false;"/>
Furthermore, since you want to get the name, date, and number of items from the text fields, you have to get the .value property to get the contents of the input fields, like so:
myData.name = document.getElementById("name").value;
myData.date = document.getElementById("date").value;
myData.numItems = parseInt(document.getElementById("number of items").value);
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
I'm too cheap to buy something nice
<script>
function calculateTotal()
{
alert("hai");
var price="4.25";
var taxRate="0.07";
var shipRate="0.02";
var name = document.getElementById("name");
var date = document.getElementById("date");
var numItems = document.getElementById("number_of_items").value;
alert(numItems);
var itemTotal = numItems * price;
var taxTotal = (numItems * price) * taxRate;
var shipTotal = (numItems * price) * shipRate;
document.writeln("Total Items:"+itemTotal+"\tTax :"+taxTotal+"\tshipTotal:"+shipTotal);
}
</script>
<form>
<p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
<p>
<label>Number of items: <input type="number" name="number_of_items" id="number_of_items" tabindex="10"/></label>
</p>
<input type="submit" onclick="calculateTotal()"/>
</form>
</body>
</html>
alert is just for to know method is calling or not, Hope this will help you
I am trying to make an annual salary calculator using Javascript. Here is what I have so far:
<div id="fulldiv">
<p> Enter the following information to calculate your annual salary.</p>
<p>Hourly Wage:
<input type="text" name="wage" id="txt_wage" value ="0.00"/></p>
<p>Hours Per Week:
<input type="text" name="hours" id="txt_hours" value= "0.0"/> <br/><br/>
<button value="calculate" onclick="calcSalary()">Calculate</button></p>
<p id="results"></p>
<script type="text/javascript">
function calcSalary() {
var wage_element = document.getElementById('txt_wage');
var wage = parseInt(wage_element.value);
var hours_element = document.getElementById('txt_hours');
var hours = parseInt(hours_element.value);
var calculate = wage_element * hours_element * 52;
document.getElementByID('results').innerHTML = calculate;
}
</script>
</div>
When I click the button, nothing happens. Any thoughts?
Some typos in there. I have slightly rewritten and simplified the code to ensure the a) your calculations are on the value of the inputs and b) you are using labels to provide the text relative to the inputs - not p's.
function calcSalary() {
var wage = parseFloat(document.getElementById('txt_wage').value);
var hours = parseFloat(document.getElementById('txt_hours').value);
var calculate = wage * hours * 52;
document.getElementById('results').innerHTML = calculate;
}
<div id="fulldiv">
<p> Enter the following information to calculate your annual salary.</p>
<label for="txt_wage">Hourly Wage:</label>
<input type="text" name="wage" id="txt_wage" value ="0.00"/>
<label for="txt_hours">Hours Per Week:</label>
<input type="text" name="hours" id="txt_hours" value= "0.0"/>
<br/><br/>
<button value="calculate" onclick="calcSalary()">Calculate</button>
<p id="results"></p>
</div>
You code needs to be adjusted
var calculate = wage_element * hours_element * 52;
Should be changed into
var calculate = wage * hours * 52;
The problem is that you're calculating the element instead of the values.
#Gerard beat me to it by a minute, but here's the working code.
<div id="fulldiv">
<p> Enter the following information to calculate your annual salary.</p>
<p>Hourly Wage:
<input type="text" name="wage" id="txt_wage" value ="0.00"/></p>
<p>Hours Per Week:
<input type="text" name="hours" id="txt_hours" value= "0.0"/> <br/><br/>
<button value="calculate" onclick="calcSalary()">Calculate</button></p>
<p id="results"></p>
<script type="text/javascript">
function calcSalary() {
var wage_element = document.getElementById('txt_wage');
var wage = parseInt(wage_element.value);
var hours_element = document.getElementById('txt_hours');
var hours = parseInt(hours_element.value);
var calculate = wage * hours * 52;
document.getElementById('results').innerHTML = calculate;
}
</script>
</div>
I'm new in coding , there is a question that someone gave me and I can't find the right answer , this is the question :
Create an HTML form with one field and button.On button click,get the input,and return the sum of the previous value and the current input value.The value is 0 and input is 5->output is 5,then value is 5,input is 6-> output is 11 and etc.
I tried few things nothing even close ,
if someone can give me the answer Ill be much appreciated , thanks.
There you go, but you should try doing it yourself. it's pretty easy to google things like "on button click" etc.
var total = 0;
$('.js_send').click(function(){
total += parseInt($('.number').val());
$('.total').html(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="0" class="number"/>
<input type="button" value="send" class="js_send"/>
<div class="total">0</div>
Here's a JQuery free version
var oldInput = 0,
newInput,
outPut;
document.querySelector("#showSum").onclick = function() {
newInput = parseInt(document.querySelector("#newInput").value),
outPut = newInput + oldInput,
oldInput = outPut,
document.querySelector("#result").innerHTML = outPut;
};
#result {
width: 275px;
height: 21px;
background: #ffb6c1;
}
<input type="number" value="0" id="newInput">
<button id="showSum">Show Results</button>
<br>
<div id="result"></div>
Here is the solution to your problem. Put all below code into a html file and name it as index.html, then run the html page.
<html>
<head>
<title></title>
</head>
<body>
Output : <label id="output">0</label>
<form method="get" action="index.html">
Your Input: <input type="text" id="TxtNum"/>
<input type="hidden" id="lastvalue" name="lastvalue" />
<input type="submit" onclick="return doSum();" value="Sum" />
</form>
<script>
//- get last value from querystring.
var lastvalue = getParameterByName('lastvalue');
if (lastvalue != null) {
document.getElementById("lastvalue").value = lastvalue;
document.getElementById("output").innerHTML = lastvalue;
}
/*
* - function to calculate sum
*/
function doSum() {
var newvalue = 0;
if(document.getElementById("TxtNum").value != '')
newvalue = document.getElementById("TxtNum").value;
var lastvalue = 0;
if(document.getElementById("lastvalue").value != '')
lastvalue = document.getElementById("lastvalue").value;
document.getElementById("lastvalue").value = parseInt(newvalue) + parseInt(lastvalue);
output = parseInt(newvalue) + parseInt(lastvalue);
}
/*
* - function to get querystring parameter by name
*/
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>
</body>
</html>
If you are doing it in server side, You could have a static variable and update it on button click. More like
public static int prevValue;
public int buttonclick(.....){
int sum = textboxValue + prevValue;
prevValue = textboxValue;
return sum;
}
here is your solution
<script type="text/javascript">
var sum=0;
function summ()
{
localStorage.setItem("value",document.getElementById("text").value);
var v=localStorage.getItem("value");
sum=sum+parseInt(v);
alert(sum);
}
</script>
<html>
<input id="text">
<button id="submit" onclick="summ()">sum</button>
</html>
It will be pretty easy.
Created CodePen
http://codepen.io/anon/pen/eJLNXK
function getResult(){
var myinputValue=document.getElementById("myinput").value;
var resultDiv=document.getElementById("result");
if(myinputValue && !isNaN(myinputValue)){
resultDiv.innerHTML=parseInt(myinputValue) + (resultDiv.innerHTML ? parseInt(resultDiv.innerHTML) : 0);
}
}
<input type="text" id="myinput">
<button id="btngetresult" onclick="getResult()">GetResult</button>
<p>
Result:
<div id="result"></div>
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
<script type="text/javascript">
function sum() {
var t1 = parseInt(document.getElementById("t1").value);
var t2 = parseInt(document.getElementById("pre").value);
document.getElementById("result").innerHTML = t1+t2;
document.getElementById("pre").value = t1;
}
</script>
</head>
<body>
<div>
<form method="get" action="">
<input type="text" name="t1" id="t1">
<input type="button" value="get sum" name="but" onclick="sum()">
<input type="hidden" name="pre" id="pre" value="0">
</form>
</div>
<div id="result"></div>
</body>
</html>