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>
Related
I have a basic js function that connects to my html file. I want the user to input a number and then the function will count up to that number. As it counts it will display a circle with each number. So, input 3 and you'll see three circles counting 1, 2, 3 horizontally on the page.
When I call the function and hard code an input like:
display(9)
it works fine.
I console log my user input, I console log as I loop through and it's counting just fine, but for some reason,
const button = document.getElementById("button");
const main = document.querySelector("main");
let number = "";
function display(num) {
for (let i = 1; i <= num; i++) {
console.log("in the loop " + i);
number += `<div>${i}</div>`;
}
}
button.addEventListener('click', () => {
let input = parseInt(document.getElementById("input").value);
console.log(input);
display(input);
});
document.getElementById("display").innerHTML = number;
<h1 class="h1">Test Form</h1>
<input class="input" id="input" type="text" />
<input type="button" id="button" value="Enter" />
<p class="display" id="display"></p>
it won't display anything using user input.
My code is below. Thoughts? And thank you for the help!
You just add the following statements to the end of display function to make it work.
let displayDiv=document.getElementByI("display");
displayDiv.innerHTML=number;
I would like to make major of basic math functions (addition, subtraction, ect.) to develop in JavaScript. Input parameters should be from HTML webpage, than do the in JavaScript and return result on the same HTML page.
function math() {
//document.getElementById("frm1").innerHTML;
var numb = document.getElementById("number").innerHTML;
var mod = document.getElementById("modifier").innerHTML;
console.log(numb);
console.log(mod);
var sum = 1; //numb + mod; //the 1 is a placeholder
console.log(sum);
sum = document.getElementById("sum").innerHTML;
}
<form id="frm1" action="randScript.js">
Number: <input type="int" name="number" id="number"><br> Modifiers: <input type="int" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id="sum"></p>
Your form tag has an action attribute. This means the page will submit your information to the specified page. You can use jQuery to prevent the form from submitting.
$("#yourFormId").on("submit",function(event){event.preventDefault()})
You can also edit the forms action attribute itself to prevent it from submitting.
<form id="frm1" action"javascript:void(0);">
First: The type is text - there is no "int" thing
Number: <input type="text" name="number" id="number">
Second: if we read a bit documentation we figure also out how to get the alue into the JS part
var numb = document.getElementById("number").value;
here you can now do your further homework ;)
Third: Get things back:
either use another input. They work two ways.
document.getElementById("result").value="I did not do my homework alone"
or you place a div somewhere with an id
<div id="result"> </div>
and now you can really use innerHTML in js
document.getElementById("result").innerHTML="I am too lazy";
The rest and to put it all together is now up to you :) Have fun to study :)
Try that if you want to display the sum at the html element:
document.getElementById("sum").innerHTML = sum;
But a more precise Question would help!
There is no int type for form inputs in HTML you can learn here about input types: HTML form input types
<form id="frm1" >
Number1: <input type="number" name="number" id="number1"><br>
Number2: <input type="number" name="number" id="number2"><br>
Modifiers: <input type="text" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id = "sum"></p>
<script type="text/javascript">
function math() {
var numb1 = parseInt(document.getElementById("number1").value);
var numb2 = parseInt(document.getElementById("number2").value);
var mod = document.getElementById("modifier").value;
if(mod == '+'){
var sum = numb1 + numb2;
}else if(mod == '-'){
var sum = numb1 - numb2;
}else if(mod == '*'){
var sum = numb1 * numb2;
}
if(sum === undefined){
alert('invalid inputs');
return false;
}else{
document.getElementById("sum").innerHTML = sum;
}
return true;
}
To retrieve inputs values properly use value rather then innerHtml.
Retrieved values are strings so you need to parse them to numbers (with parseInt) before using them in math.
function math() {
const numb = document.getElementById("number").value;
const mod = document.getElementById("modifier").value;
sum = document.getElementById("sum").innerText = parseInt(numb) + parseInt(mod);
}
I am trying to make a form field that asks the user which countries it has visited, and limit this to 10. So the user has to give ten inputs in one form field.
But when I click on the submit button it won't let the user enter a second time. It just calls the function that displays the first country that the user has entered.
How do I keep the values the user is entering in the form field and when the user has entered all the ten countries, then click on submit to call the function that would display all the countries?
function validateForm() {
var repeat = new Array();
for (i = 0; i < 10; i++) {
var x = document.forms["form1"]["countries"].value;
repeat.push(x);
}
document.write(repeat);
}
<form id="form1">
Enter the countries:
<input type="text" id="countries"><br><br>
<input type="button" onclick="validateForm()" value="Click Me!">
It keeps on displaying that one country the user has entered 10 times, instead of letting user enter ten countries and then displaying then when clicking on submit.
This will do what you sketched out. I don't think it's a very good way of asking a user for 10 items, as there's no feedback as to how many they've entered, nor the ability to edit the items once entered, nor a way of clearing the list to enter 10 more. Also, this will never actually submit the list. But this meets the requirements as stated:
var repeat = [];
function validateForm() {
var countries = document.getElementById("countries");
if (repeat.length < 10) {
var x = countries.value;
repeat.push(x);
countries.value = "";
countries.focus();
}
if (repeat.length === 10) {
var hid = document.getElementById("list");
hid.value = repeat.join('|');
console.log(hid.value);
var ul = document.getElementById("display");
ul.innerHTML = "";
for (var i = 0; i < 10; i++) {
ul.innerHTML += `<li>${repeat[i]}</li>`;
}
document.getElementById("done").style.display = "block";
}
}
window.onload = function() {
document.getElementById("click").addEventListener("click", validateForm);
};
<form id="form1">
Enter the countries:
<input type="text" id="countries"><br><br>
<input type="button" id="click" value="Click Me!">
<input type="hidden" id="list" name="listOfCountries">
</form>
<br>
<div id="done" style="display:none">
Countries entered:
<ul id="display"></ul>
</div>
Note that the hidden fields listOfCountries will contain the list of 10 countries, delimited by a pipe symbol "|". It's up to you to post that to a server.
You could use a global array for the countries and store until ten countries in the array.
function enterCountry() {
var input = document.getElementById('country');
if (input.value && countries.length < 10) {
countries.push(input.value);
input.value = '';
input.placeholder = 'insert ' + (10 - countries.length);
}
if (countries.length === 10) {
input.placeholder = 'ready';
document.getElementById('allCountries').innerHTML = countries.join(', ');
}
}
var countries = [];
<form id="form1">
Enter the countries:
<input type="text" id="country" placeholder="insert 10"><br><br>
<input type="button" onclick="enterCountry()" value="Click Me!">
</form>
<div id="allCountries"></div>
Hey you can get multiple input value on submit with jquery
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
console.log( $( this ).serialize() );
});
Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim
I'm getting an undefined error and don't know why this isn't working.
It's supposed to divide the rent by the amount of roommates:
function splitRent() {
var roommates = document.getElementById("rent");
var rent = document.getElementById("rent");
var rentEach = rent / roommates;
if (document.getElementById("submit") == true) {
document.write("You each should pay" + " " + rentEach)
} else {
document.alert("Gimme info")
}
};
<h1>Roommate Room Splitter</h1>
<form id="myForm">
Roommates:
<input type="text" name="roommates" id="roommates">
<br/>Rent:
<input type="text" name="rent" id="rent">
<br/>
<input type='submit' id='submit' value='Submit' onclick="splitRent()" />
</form>
You want to take the value of the fields, not the fields themselves.
document.getElementById() returns the node, but you want the value of the input field:
var rent = document.getElementById("rent").value;
Also, you're getting the value of the rent twice; you want to check the roommates as well.
var roommates = document.getElementById("roommates").value;
Lastly, document.getElementById("submit") == true doesn't mean anything: you're comparing a button node with a boolean value, which doesn't make sense. If you want to check to make sure that both fields are filled, try this:
if(roommates && rent){
//do calculations
}else{
window.alert("Enter something"); //note that it's window.alert(), not document.alert(), which is not a function
As it stands, this allows people to enter things that are not numbers; there are two things that you could do to fix that.
Use parseInt()/parseFloat() to ensure that you're extracting a number
Check that you actually have a number before doing calculations
You'd do something like this:
var rent = parseInt(document.getElementById("rent").value);
var roommates = parseFloat(document.getElementById("rooommates").value);
If you use the checking I've done above (rent && roommates), the validation will take place there (it checks for both empty and NaN values).
function splitRent() {
var roommates = parseInt(document.getElementById("roommates").value);
var rent = parseFloat(document.getElementById("rent").value);
var rentEach = rent / roommates;
if (roommates && rent) {
document.write("You each should pay" + " " + rentEach)
} else {
window.alert("Gimme info")
}
};
<h1>Roommate Room Splitter</h1>
<form id="myForm">
Roommates:
<input type="text" name="roommates" id="roommates">
<br/>Rent:
<input type="text" name="rent" id="rent">
<br/>
<input type='submit' id='submit' value='Submit' onclick="splitRent()" />
</form>
Shouldn't this be:
var roommates = document.getElementById("roommates").value;
var rent = document.getElementById("rent").value;
Do you always get "1" for your result?