I'm not sure how to add tax (7%) to my cost ($6) under Javascript. Can anyone help me?
html
<div class="item main">
<h1>Enter a Title</h1>
<p>Please enter a title to calculate how much it will cost<br>
<input id = "titleBox" type = "text">
<button onclick="calculateCost()">Enter</button>
</p>
<p id= "output">Result</p>
</div>
Javascript
var titleName;
var cost = 6;
function calculateCost() {
titleName = document.getElementById("titleBox").value;
var titleLetters;
titleLetters = titleName.length;
var spaceCount = (titleName.split(" ").length - 1);
document.getElementById("output").innerHTML = "$" + (titleLetters - spaceCount) * cost;
/* "Red Car" "Red" "Car" */
}
It is pretty basic(just simple math), here is the implementation:
var titleName;
var cost = 6;
const tax = 7/100; // Added the tax
function calculateCost() {
titleName = document.getElementById("titleBox").value;
var titleLetters;
titleLetters = titleName.length;
var spaceCount = (titleName.split(" ").length - 1);
document.getElementById("output").innerHTML = "$" + ((titleLetters - spaceCount) * cost*(1+tax)); // Since we have to add tax we have to use 1+tax
/* "Red Car" "Red" "Car" */
}
Note: scroll to the right to see the upgraded fromula since it got out of the stack overflow code box
Related
So I am working on a jeopardy web app and I have a portion of the app where players can create as many teams as they need and give them a custom name.
HTML
<!--Score Boards-->
<div id="teamBoards">
<div id="teams">
</div>
<div id="addTeams">
<h3>Add Teams</h3>
<input type="text" placeholder="Enter Team Name" id="teamName">
<button id="addTeam">Add a Team</button>
</div>
</div>
JS
var div = document.createElement("div");
div.className = "Teams"
var teamNameElement = document.createElement("h3");
var teamName = $('#teamName').val();
teamNameElement.textContent = teamName;
var score = document.createElement("h4");
score.textContent = "0";
score.id = "score"+teamName;
score.className = "score";
var plusButton = document.createElement("button");
plusButton.textContent = "+";
plusButton.id = "plus"+teamName;
plusButton.className = "plus";
var minusButton = document.createElement("button");
minusButton.textContent = "-";
minusButton.id = "minus"+teamName;
minusButton.className = "minus";
div.appendChild(teamNameElement);
div.appendChild(score);
div.appendChild(plusButton);
div.appendChild(minusButton);
var placementDiv = document.getElementById('teams');
placementDiv.appendChild(div);
The code above creates a team name, a place for the score with 0 preset, and a plus and minus button for points.
I start to have trouble when I go to add or subtract points by 100.
JS
$(plusButton).on('click', add);
$(minusButton).on('click', minus);
function add(){
var score1 = $('.score').html();
console.log(score1);
score1 = Number(score1);
score1 = score1 + 100;
console.log(score1);
$(score).html(score1);
}
function minus(){
var score1 = $('.score').html();
score1 = Number(score1);
score1 = score1 - 100;
$(score).html(score1);
}
All of the code here is in one function, so some variables from the plus and minus functions could be the variables from the code above. The problem is that I can not add points to specific teams' scoreboard through a specific id for each team score.
Here is a way to do what your looking at using more jQuery and $this selectors to work with individual teams like you want. I added some notes in the snippet below. Just run the snippet a few times and look at the comments to see how the teams are being selected.
$(function(){
var teamCount = 0;
var $teamsDiv = $("#teams");
$("#addTeam").click(function(){
//get the team name value
var teamName = $("#teamName").val();
//Create clone of html team template
var $newTeam = $("#teamTemplate").clone();
//Set an id for each team using the teamCount var
$newTeam.attr("id", "team" + teamCount);
//Set the entered text
$newTeam.find(".teamName").text(teamName);
//Set the score to zero
$newTeam.find(".score").text("0");
//Append new team to teams div
$teamsDiv = $("#teams");
$teamsDiv.append($newTeam.html());
});
//Add button press (using $("#teams").on('click'... allows for setting
//listeners on dynamically created html
$("#teams").on('click', '.plusButton', function() {
var $teamTemplate = $(this).closest(".template");
var $score = $teamTemplate.find(".score");
var teamName = $teamTemplate.find(".teamName").text();
var currentScore = parseInt($score.text());
$score.text(currentScore + 100);
$(this).closest(".template").find(".teamName");
console.log(teamName + " Score: " + $score.text());
})
//Minus button press
$("#teams").on('click', '.minusButton', function() {
//Using the "this" selector edit just the div you want.
var $teamTemplate = $(this).closest(".template");
var $score = $teamTemplate.find(".score");
var teamName = $teamTemplate.find(".teamName").text();
var currentScore = parseInt($score.text());
//Set new score text
$score.text(currentScore - 100);
//Console.log just to see what is happening
$(this).closest(".template").find(".teamName");
console.log(teamName + " Score: " + $score.text());
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--Score Boards-->
<div id="teamBoards">
<div id="addTeams">
<h3>Add Teams</h3>
<input type="text" placeholder="Enter Team Name" id="teamName">
<button id="addTeam">Add a Team</button>
</div>
<br />
<div id="teams">
</div>
</div>
<div style="display:none;" id="teamTemplate" >
<div class="template">
<span class="teamName"></span>
<button class="plusButton" type="button">+</button>
<button class="minusButton">-</button>
<span class="score">0</span>
<br />
</div>
</div>
I would highly recommend the Jquery video tutorial for getting a jump on using jQuery. It is a great tutorial that shows all the tricks to making client side code quick and easy.
Im trying to calculate a price that is depending on how many rows you use in a textarea. This is what i have come up with so far. The only problem is its won't calculate, i think i have looked at it to much or something.
Let me explain a little, first of its for som textads.
There is a flatfee for minimum of 2 rows and then additional 10 for each new row, with a maximum of 10 rows.
var flatFee = '70.00';
var perRow = '10.00';
function rowCount(area, maxlength) {
//var area = document.getElementById("textarea-1")
// trim trailing return char if exists
var text = area.value.replace(/\s+$/g, "");
var split = text.split("\n");
if (split.length > maxlength) {
split = split.slice(0, maxlength);
area.value = split.join('\n');
alert("You can not enter more than " + maxlength.toString() + " lines");
}
return false;
}
var div = $('span.rowCount');
jQuery('textarea#textarea-1').on('input', function($) {
var count = rowCount(this.value);
div.html(count.rows);
/*var additionalFees = perRow*count.rows;*/
if (count.rows > 2) {
var additionalFees = perRow * (count.rows - 2);
}
var total = parseFloat(flatFee) + parseFloat(additionalFees);
$('span.total').html(parseFloat(total.toString()).toFixed(2));
/*var total = $('span.total');*/
console.log(total);
});
<textarea cols="32" rows="10" maxlenght="320" class="form-control" name="textarea-1" id="textarea-1" placeholder="Type or paste your prompt here."></textarea>
<p>You have <span class="rowCount">0</span> rows.Total <span class="total">0</p>
Modified your function a bit. Works now
var flatFee = '70.00';
var perRow = '10.00';
function rowCount(area, maxlength) {
//var area = document.getElementById("textarea-1")
// trim trailing return char if exists
var text = area.replace(/\s+$/g, "");
var split = text.split("\n");
if (split.length > maxlength) {
split = split.slice(0, maxlength);
area.value = split.join('\n');
alert("You can not enter more than " + maxlength.toString() + " lines");
}
return {rows:split.length};
}
var div = $('span.rowCount');
jQuery('textarea#textarea-1').on('input', function($) {
var count = rowCount(this.value);
div.html(count.rows);
/*var additionalFees = perRow*count.rows;*/
var additionalFees=0;
if (count.rows > 2) {
additionalFees = perRow * (count.rows - 2);
}
var total = parseFloat(flatFee) + parseFloat(additionalFees);
//$('span.total').html(total.toString().toFixed(2));
/*var total = $('span.total');*/
console.log(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<textarea cols="32" rows="10" maxlenght="320" class="form-control" name="textarea-1" id="textarea-1" placeholder="Type or paste your prompt here."></textarea>
<p>You have <span class="rowCount">0</span> rows.Total <span class="total">0</span></p>
https://jsfiddle.net/5mcbt8ua/4/
HTML
Flat Rate / First 2 rows: 70<BR>
Additional Rows: 10 per row
<div id="compute" contenteditable="true" style="border:1px solid #ccc;">
</div>
Total Price: <font id="total">0</font>
<BR>
<font id="msg"></font>
jQuery
var flatFee = 70;
var perRow = 10;
$('#compute').keypress(function(){
$("#msg").html('Press enter to compute');
var count = $(this).find('div').length;
var total = flatFee;
if(count > 1)
{
total = flatFee + (count * 10) - 10;
}
$("#total").html(total);
});
I'm make a little calculator that convert KG in Pounds and Pounds in KG and write on an input. But, I want make this with only one button to calculate! Understand?
KG to POUNDS -> KG * 2.2046
POUNDS to KG -> POUNDS / 2.2046
Example 1:
Field 1: 50 kg
....calc...
Field 2 (result): 110.23 Pounds
Then there will be the button for me to change the function (Button of Google Translate to change the languages in every click) I click and ..
Example 2:
Field 1: 100 pounds
...calc...
Field 2 (result): 45.35
Can you understand what I do?
function calcPD(){
var pound = document.getElementById("field1").value;
var calc = quilos / 2.2046;
var resul = document.getElementById("pound").value=calcularr.toFixed(2);
}
function calcKg(){
var kg = document.getElementById("field1").value;
var calc = quilo * 2.2046;
var resul = document.getElementById("pound").value=calcular.toFixed(2);
}
funcion invert(){
???
}
I think what you're looking for is just a simple variable to keep track of what "mode" you are in. I've built an example for you to see how this would work (I used bootstrap to make it pretty, but obviously that's optional):
https://jsfiddle.net/DTcHh/13851/
HTML
<div class="container">
<div class="row">
<div class="col-xs-6">
Input:
<input id="inputNum" class="form-control" type="number"></input>
</div>
<div class="col-xs-6">
Output:
<input id="outputNum" class="form-control" type="text" disabled></input>
</div>
</div>
<span id="modeText">lbs to kg</span>
<button id="switch" class="btn pull-right">Switch</button>
</div>
Javascript
//0 = lbs to kg, 1 = kg to lbs
var mode = 0;
var inputNum = $("#inputNum");
var outputNum = $("#outputNum");
var switchMode = $("#switch");
var modeText = $("#modeText");
var calculateKgs = function() {
outputNum.val(inputNum.val()/2.2046);
};
var calculateLbs = function() {
outputNum.val(inputNum.val()*2.2046);
};
var calculate = function() {
if(mode == 0)
calculateKgs();
else
calculateLbs();
};
inputNum.change(calculate);
inputNum.keyup(calculate);
switchMode.click(function() {
if(mode) {
mode = 0;
modeText.text("lbs to kg");
}
else {
mode = 1;
modeText.text("kg to lbs");
}
calculate();
});
Sounds like you need to use innerHtml. Some basic pseudo logic for you:
var a = document.getElementById("one").innerHtml;
var b = document.getElementById("two").innerHtml;
document.getElementById("one").innerHtml = b;
document.getElementById("two").innerHtml = a;
I'm attempting to create a webpage that will allow my employees to enter a number and get a number that has run through an equation. I want it to do two simple math problems as follows and output the number that's larger.
Equations
x+150=y
x*1.5+89=z
Then display the larger variable.
I can't get it to work.
I'm pretty sure it's a major noob mistake.
<script type="text/javascript">
function updateOutput() {
//get form
var form = document.getElementById("calc");
//get output
var out = form.elements["z"];
//get two numbers
var num1 = parseInt(form.elements["x"].value);
//add 150
var num2 = 150;
//multiply 1.5;
var num3 = 1.5;
//add 89
var num4 = 89;
//amount1
var amount1;
//amount2
var amount2;
//set output depending on amount
//add
amount1.value = num1+num2;
//multiple
amount2.value = num1*num3+num4;
If amount1 > amount2 Then
out.value = amount1.value
Else
out.value = amount2.value
}
</script>
Some errors:
amount1.value only works if you define amount as Object, and it doesn't need to be object here. Same for amount2.
if else notation error
Better go to some tutorial sites like w3school or codecademy or buy some books.
Changes of your code, with added form, input to demonstrate.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="calc">
<input type="number" name="x"/>
<input type="number" name="z"/>
</form>
<button onclick="updateOutput();">click</button>
<script>
function updateOutput() {
//get form
var form = document.getElementById("calc");
//get output
var out = form.elements["z"];
//get two numbers
var num1 = parseInt(form.elements["x"].value);
//add 150
var num2 = 150;
//multiply 1.5;
var num3 = 1.5;
//add 89
var num4 = 89;
//amount1
var amount1;
//amount2
var amount2;
//set output depending on amount
//add
// It's ok to just assign value to them.
amount1 = num1+num2;
//multiple
amount2 = num1*num3+num4;
// Also here, don't use amountX.value.
if (amount1 > amount2) {
out.value = amount1
} else {
out.value = amount2
}
}
</script>
I previously posted a code with the similar way and I am still having problems with it. this time I get 100.0712.5 when I put 10 as the bill, 7 for the sales tax and 25 for the tip. I am really new to Javascript coding and I have literally been spending hours trying to figure this out I need help.
<html>
<head>
<script type="text/javascript">
function applyTax(){
var inputAmount = document.getElementById( 'dollars' ).value;
var salesTax = document.getElementById( 'tax' ).value;
var tip = document.getElementById( 'tip' ).value;
var totalAmount = (salesTax/100) + (inputAmount);
var tipprcnt = (tip/100) * (inputAmount);
var Grandtotal = (inputAmount + (totalAmount*1) + (tipprcnt*1));
//document.getElementById( 'requestedAmount' ).innerHTML = tipprcnt;
//document.getElementById( 'requestedTax' ).innerHTML = totalAmount;
document.getElementById( 'requestedGrand' ).innerHTML = Grandtotal;
}
</script>
</head>
<body>
<h1>Sales Tax + Tip Calculator</h1>
<p>Type in your price (dollar amount). Click the "Calculate" button to receive your total.
</p>
<p>
What is the bill amount?: $<input type="text" id="dollars" /> <br>
What is the sales tax?:<input type="text" id="tax" />%<br>
how much do you want to tip?:<input type="text" id="tip" />%
<input type="button" onclick="applyTax();" value="Calculate" />
</p>
</h2>The Grand Total is:</h2>
<div id="requestedAmount"> </div>
<div id="requestedTax"> </div>
<div id="requestedGrand"> </div>
<p>Home
</body>
</html>
You were adding them as string, use parseFloat instead
http://plnkr.co/edit/6pN2Ug5qxcOSUjE5AnhJ?p=preview
function applyTax(){
var inputAmount = parseFloat(document.getElementById( 'dollars' ).value);
var salesTax = parseFloat(document.getElementById( 'tax' ).value);
var tip = parseFloat(document.getElementById( 'tip' ).value);
var taxprcnt = (salesTax/100) * (inputAmount);
var tipprcnt = (tip/100) * (inputAmount);
var Grandtotal = inputAmount + taxprcnt + tipprcnt;
document.getElementById( 'requestedGrand' ).innerHTML = Grandtotal.toFixed(2); // Round to 2 decimals
}
You should use parseFloat() to convert the inputs to numbers.
You need to multiply the input amount by the tax percentage, not add them.
You should round off the final result, because people don't want to see fractional pennies.
DEMO
When I enter $10 amount, 7% tax, 25% tip, the total is $13.20.
Use Number(input.value) by every input to convert the string values into numbers. You can use parseInt() or parseFloat instead of Number() if you want. The first converts to integer, the second converts to numbers with decimal points.
Btw forget the overusage of () and *1, it is just noise for others...
Your variable names are confusing, but I guess you wanted something like this:
var amountInput = document.getElementById("dollars");
var taxInput = document.getElementById("tax");
var tipInput = document.getElementById("tip");
var amount = Number(amountInput.value);
var taxPercent = Number(taxInput.value);
var tipPercent = Number(tipInput.value);
var grandTotal = Math.round(amount * (100 + taxPercent + tipPercent)) / 100;
var grandTotalOutput = document.getElementById("requestedGrand");
grandTotalOutput.innerHTML = grandTotal;