I am trying to develop a simple piece of code.. I created a calculator to calculate Celcius/Kelvin/Fahrenheit based on HTML input. The code seems to be working. The correct answers appear but then dissapear in a split second, the browser seems to 'refresh'. Am i missing something?
Html code:
<html>
<body>
<form>
<label for="degrees">Degrees: </label>
<input type="text" name="degrees" id="degrees">
<label for="calc_type">Type: </label>
<select name="calc_type" id="calc_type">
<option value="celcius">Celcius</option>
<option value="kelvin">Kelvin</option>
<option value="fahrenheit">Fahrenheit</option>
</select>
<input type="submit" value="Submit" onclick="myFunction()">
</form>
<table style="width: 100px">
<tr>
<th>Celcius: </th>
<th id="celsius_value">0</th>
<tr></tr>
<th>Fahrenheit: </th>
<th id="fahrenheit_value">0</th>
<tr></tr>
<th>Kelvin: </th>
<th id="kelvin_value">0</th>
</tr>
</table>
</body>
<script src="js/celcius_calulator.js"></script>
</html>
JS code:
function myFunction() {
var degrees = document.getElementById('degrees').value
var calc_type = document.getElementById('calc_type').value
if (calc_type === "celcius") {
cC(degrees);
} elseif (calc_type === "fahrenheit"); {
fC(degrees);
} elseif (calc_type === "kelvin"); {
kC(degrees)
}
}
function cC(degrees) {
celcius_value = degrees;
kelvin_value = degrees * 273.15;
fahrenheit_value = degrees * 1.8 + 32;
document.getElementById('celsius_value').innerHTML = degrees;
document.getElementById('fahrenheit_value').innerHTML = fahrenheit_value;
document.getElementById('kelvin_value').innerHTML = kelvin_value.toFixed(2);
}
function fC(degrees) {
celcius_value = Math.round(degrees - 32) / 18 * 10;
kelvin_value = degrees + 459.67 / 1.8;
fahrenheit_value = degrees;
document.getElementById('celsius_value').innerHTML = degrees;
document.getElementById('fahrenheit_value').innerHTML = fahrenheit_value;
document.getElementById('kelvin_value').innerHTML = kelvin_value.toFixed(2);
}
function kC(degrees) {
celcius_value = degrees - 273.15
fahrenheit_value = degrees * 1.8 - 459.67;
kelvin_value = degrees;
document.getElementById('celsius_value').innerHTML = degrees;
document.getElementById('fahrenheit_value').innerHTML = fahrenheit_value;
document.getElementById('kelvin_value').innerHTML = kelvin_value.toFixed(2);
}
The submit button will post the form-content to whatever you specified as the form's target through <form action="target-url">. As you didn't specify anything, it will simply post the forms content to the current page.
You will have to do something like
document.querySelector('form').addEventListener('submit', e => e.preventDefault())
to prevent the form from being submitted, which will then again prevent the page from reloading.
You can then also do your evaluation logic in the event listener so you don't end up with two event listeners (One for the submit button, one for the form submit event).
The simplest answer would be to pass an event as parameter in myFunction(event) and do event.preventDefault(). Just pass event as param the following ->
<input type="submit" value="Submit" onclick="myFunction(event)">
and in your js file do this ->
function myFunction(event) {
event.preventDefault();
var degrees = document.getElementById('degrees').value
var calc_type = document.getElementById('calc_type').value
if (calc_type === "celcius") {
cC(degrees);
} elseif (calc_type === "fahrenheit"); {
fC(degrees);
} elseif (calc_type === "kelvin"); {
kC(degrees)
}
You can make the below change in your code.
<input type="button" value="Submit" onclick="myFunction()">
Hope this solve your problem.
Related
<form onsubmit="calculos(); return false;">
<label for="gasto">
<span> Valor </span>
<input
required
type="number"
id="gasto"
class="gasto"
name="gasto"
placeholder="Valor.."
/>
</label>
<input type="submit" value="submit"/>
</form>
script trying to take that input into a variable for a function to
return that inpunt and * to print in web
<script language="javascript">
function calculos() {
document.getElementById("gasto").value;
var num1 = document.getElementById("gasto").value;
Honorarios = num1 * 0.3;
Escribania = num1 * 0.2;
sellos = num1 * 0.05;
return (Honorarios, Escribania, sellos);
console.log(gasto);
console.log(Honorarios);
console.log(Escribania);
console.log(sellos);
alert(gasto, Honorarios, Escribania, sellos);
}
calculos();
</script>
sorry if i dont explain good enough im learing html and js and wanted to make a calculator that you input a amount and the algorithm gives you back that amount * by 0.05 and others thanks
I edited your code, and removed the unnecessary lines, also moved the label HTML element which was badly placed, it works now, watch out for console log.
I also combined all results into a single string before alert line.
function calculos() {
document.getElementById("gasto").value;
var num1 = document.getElementById("gasto").value;
Honorarios = num1 * 0.3;
Escribania = num1 * 0.2;
sellos = num1 * 0.05;
console.log(Honorarios);
console.log(Escribania);
console.log(sellos);
let allOfThem = `Honorarios: ${Honorarios}
Escribania: ${Escribania}
sellos: ${sellos}`
alert(allOfThem);
}
//calculos(); This function SHOULD never be here, as it will be called everytime.
<form onsubmit="calculos(); return false;">
<label for="gasto">
<span> Valor </span>
</label> <!-- This was moved here to the right place, it was at the end of form -->
<input
required
type="number"
id="gasto"
class="gasto"
name="gasto"
placeholder="Valor.."
/>
<input type="submit" value="submit"/>
</form>
Bit of a newbie question here. Trying to implement a simple tip calculator and display the results below the form that the user submits with the bill amount and the tip percentage. The function that fires on submit successfully does the calculation - the correct amounts are alerted (the alerts are just in for checking), however the span elements either don't get the inner HTML or the page immediately reloads so that they don't persist. How do I get the amounts to display and remain?
<form id="tipCalculator">
<label for="billAmount">Enter Bill Amount:</label>
<input type="number" name="billAmount" id="billAmount">
<label for="tipPercent">Enter Tip Percentage:</label>
<input type="number" name="tipPercent" id="tipPercent">
<input type="submit" onclick= "calcTip()" name="submitButton" value="Calculate Tip">
</form>
<div id=displayResultArea>
<p>Tip Amount:<span id=displayTipAmount></span></p>
<p>Total Bill:<span id=displayTotalAmount></span></p>
</div>
</main>
<script type="text/javascript">
function calcTip() {
let billAmnt = document.getElementById('billAmount').value;
let tipPrcnt = document.getElementById('tipPercent').value;
let billAmntNum = parseFloat(billAmnt);
let tipPrcntNum = parseFloat(tipPrcnt);
let tipAmnt = billAmntNum * (tipPrcntNum / 100);
let billTotal = billAmntNum + tipAmnt;
alert(tipAmnt);
alert(billTotal);
document.getElementById('displayTipAmount').innerHTML = tipAmnt;
document.getElementById('displayTotalAmount').innerHTML = billTotal;
}
The reason you are seeing the page reload is because you are submiting the form which is posting a request to the backend.
You can prevent the request being posted by adding prevent default like so:
function calcTip() {
event.preventDefault()
let billAmnt = document.getElementById('billAmount').value;
let tipPrcnt = document.getElementById('tipPercent').value;
let billAmntNum = parseFloat(billAmnt);
let tipPrcntNum = parseFloat(tipPrcnt);
let tipAmnt = billAmntNum * (tipPrcntNum / 100);
let billTotal = billAmntNum + tipAmnt;
alert(tipAmnt);
alert(billTotal);
document.getElementById('displayTipAmount').innerHTML = tipAmnt;
document.getElementById('displayTotalAmount').innerHTML = billTotal;
}
If you want to submit the form elsewhere i would reccomend changing the submit input to the following as it may be confusing to have two submit buttons
<button onclick="calcTip()" name="submitButton" >Calculate Tip</button>
Use need to prevent default form behaviour, use event.preventDefault();
function calcTip(event) {
let billAmnt = document.getElementById('billAmount').value;
let tipPrcnt = document.getElementById('tipPercent').value;
let billAmntNum = parseFloat(billAmnt);
let tipPrcntNum = parseFloat(tipPrcnt);
let tipAmnt = billAmntNum * (tipPrcntNum / 100);
let billTotal = billAmntNum + tipAmnt;
//alert(tipAmnt);
//alert(billTotal);
event.preventDefault();
document.getElementById('displayTipAmount').innerHTML = tipAmnt;
document.getElementById('displayTotalAmount').innerHTML = billTotal;
}
<input type="submit" onclick= "calcTip(event)" name="submitButton" value="Calculate Tip">
Try to change to below line input type from submit to button
<input type="button" onclick="calcTip()" name="submitButton" value="Calculate Tip">
I'm trying to make a game where you enter a number into a textbox and then click on Lock In.
You can then not change your answer.
After that you click on Random Number and it will give you a random number 1-50.
But the problem is that I want to make it where you have to click Lock In before you can find out the random number.
This is because you can just not click Lock In and then change it so that it is right.
My code for this is below:
function numFunction() {
var x = Math.floor((Math.random() * 50) + 1);
document.getElementById("randnum").innerHTML = x;
start.disabled = true;
reload.disabled = true;
}
function btnFunction() {
document.getElementById("answerbox").readOnly = true;
}
function revFunction() {
document.getElementById("rnum").disabled = false;
}
<div id="randbutton">
<button id="rnum" onclick="numFunction()">Random Number</button>
<p id="randnum"></p>
<input type="text" name="answerbox" size="20" id="answerbox">
<div id="lockbtn">
<button onclick="btnFunction();revFunction();">LockIn</button>
<div id="resetbtn"></div>
<button id="relbtn" onclick="relFunction()">Reset</button>
</div>
</div>
You are really close. You can just add "disabled" to your button, and then when the user locks in their answer, enable it again.
Additionally, it's not best practice to split your JavaScript into a bunch of different script tags. Put them all in one place.
function numFunction() {
var x = Math.floor((Math.random() * 50) + 1);
document.getElementById("randnum").innerHTML = x;
start.disabled = true;
reload.disabled = true;
}
function btnFunction() {
document.getElementById("answerbox").readOnly = true;
}
function revFunction() {
document.getElementById("rnum").disabled = false;
}
function relFunction() {
location.reload();
}
<div id="randbutton">
<button id="rnum" onclick="numFunction()" disabled>Random Number</button>
<p id="randnum"></p>
<input type="text" name="answerbox" size="20" id="answerbox">
<div id="lockbtn">
<button onclick="btnFunction();revFunction();">LockIn</button>
<div id="resetbtn"></div>
<button id="relbtn" onclick="relFunction()">Reset</button>
</div>
</div>
you could use the disabled property on the button to start.
<button type="button"id="lock" onclick="enableNum()">Lock in</button>
<button type="button"id="randomNum" disabled>Random Number</button>
Then when someone enters the number, you would have a function that detects the input and enables the button.
function enableNum() {
document.getElementById("randomNum").disabled = false;
}
I'm working on a personal project where I'd like to take user input via a form's text boxes, perform a calculation on it, and display the result on the same page. I work in a restaurant and would like to simplify the process of calculating the cost of a cocktail. I'm new to Javascript and this is my first proper project. I'm having difficulty figuring out what to do after storing the user input into a variable. I have created an object "drinkPrices" with the three different categories of drink types under the "name" keyword, the respective prices under the other keywords, and then a method that calculates the prices. I'm unsure if this approach is correct and ANY feedback/suggestions/help would be much appreciated.
Main difficulties:
1. Am I storing the user input correctly?
2. How do I take the user input and reference it to the method in the object I have created?
3. How do I display the results of the calculation on the page?
<!DOCTYPE html>
<html lang="en">
<head>
<script src="submitAlert.js"></script>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form id="theform">
Enter Spirit Name:<br>
<input type="text" id="sname" name="spiritname"><br>
Enter Spirit Amount (in ounces):<br>
<input type="text" id="samount" name="spiritamount">
<br><br>
<input type="submit" value="submit" onclick="return foo();" />
</form>
</body>
<p id="outputarea"> ...Output area is right here...</p>
</html>
Javascript:
var drinkPrices = {
name: ['rail', 'call', 'premium'],
railPrice: 4,
callPrice: 6,
premiumPrice: 8,
quantity: 0,
calculatePrice: function() {
if (name === 'rail') {
calculatePrice = quantity * railPrice;
} else if (name === 'call') {
calculatePrice = quantity * callPrice;
} else if (name ==='premium') {
calculatePrice = quantity * premiumPrice;
}
return this.calculatePrice;
}
}
//this is the code I have for when the user hits submit. I am missing a lot//
function foo() {
var a = document.getElementById("sname").value;
var b = document.getElementById("samount").value;
alert("Submit button clicked!");
return true;
}
Just use a name-price map:
const price = {
rail:2,
call:4,
premium:6
};
Then you can simply get the price:
function calculatePrice() {
const name = document.getElementById("sname").value;
const amount = document.getElementById("samount").value;
alert(`It costs ${amount * prices[name]}`);
}
Hint: Don't use a form if you dont want to send something to the server (just use <input> only), it makes things complicated, and give appropriate names to variables and functions!
Here are some improvements for your further coding:
Replace input elements with select lists when you dealing with a predefined list of options, in this way you prevent accedential typos by the user.
When you use select and you're only interessted in corresponding values, use the value attribute on option tags.
When you need numerical inputs, use <input type="number"> or <input type="range" min="0" max="100" step="1"> (min/max/step are optional and can be added to number-inputs too).
Use the onsubmit on forms instead of onclick on buttons to let the browser validate the inputs (part of better practice).
Here I've hacked together an example:
document.querySelector('#theform').addEventListener('submit', function(e) {
e.preventDefault();
let price = this.spirit.value * 1;
let amount = this.spiritamount.value * 1;
let total = (price * amount).toFixed(2);
document.querySelector('#outputarea').textContent = total;
});
<form id="theform">
Enter Spirit Name:<br>
<select name="spirit">
<option value="4">rail</option>
<option value="6">call</option>
<option value="8">premium</option>
</select><br>
Enter Spirit Amount (in ounces):<br>
<input type="number" name="spiritamount" value="1">
<br><br>
<button>Calculate</button>
</form>
<p id="outputarea">0.00</p>
Here is another example with listed entries:
let receipt = {};
const prices = {
'rail': 4,
'call': 6,
'premium': 8
};
// clear the receipt
document.querySelector('#reset').addEventListener('click', function(e) {
e.preventDefault();
receipt = {};
document.querySelector('#outputarea').innerHTML = '';
});
document.querySelector('#theform').addEventListener('submit', function(e) {
e.preventDefault();
let spirit = this.spirit.value;
let amount = this.spiritamount.value * 1;
if(spirit in receipt) {
receipt[spirit] += amount;
} else {
receipt[spirit] = amount;
}
let list = '';
let total = 0;
for(const e in receipt) {
let sum = prices[e] * receipt[e];
list += `<div>${e} x ${receipt[e]} = ${sum.toFixed(2)}</div>`;
total += sum;
}
list += `<hr>${total.toFixed(2)} ยค`;
document.querySelector('#outputarea').innerHTML = list;
})
<form id="theform">
Select Spirit: <select name="spirit">
<option>rail</option>
<option>call</option>
<option>premium</option>
</select><br>
Enter Spirit Amount (in ounces): <input type="number" name="spiritamount" value="1"><br><br>
<button>Add to receipt</button> or <button id="reset">Reset</button>
</form>
<p id="outputarea"></p>
I am trying tot get my javascript code to redirect to the Index.html page if the variable money is equal to 100. Here is the html form code:
<form id = "form" action = "">
<h1> Enter the amount of money you would like to spend on your next trip. </h1><br>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="text" name="money" class="form-control">
</div>
<br>
<button type="submit" class="btn btn-default" onclick = "MoneyForTrip()">Show Trips</button>
</form>
and the javascript:
var money;
function MoneyForTrip()
{
money = parseInt(
document.getElementById('form').money.value);
if (money == 100)
{
window.location="Index.html";
}
else
{
window.alert("Enter another number");
}
}
Any idea how I can get it to redirect to Index.html if money is equal to 100?
Try this.
window.location.replace("Index.html")
or
window.location.href = "Index.html"
Also take a look at this Stack Answer.
Use the submit event instead of button's click event:
var money;
var form = document.getElementById('form');
form.onsubmit = function(e) {
e.preventDefault();
money = parseInt(document.getElementById('form').money.value);
if (money == 100){
window.location="Index.html";
}
else{
window.alert("Enter another number");
}
}
Demo: http://jsfiddle.net/xzjW3/
try
<input type="text" name="money" id="moneyfortrip" class="form-control">
var money;
function MoneyForTrip()
{
money = parseInt(
document.getElementById('moneyfortrip').value);
if (money == 100)
{
window.location="Index.html";
}
else
{
window.alert("Enter another number");
}
}