get rid of the text area on a form once clicked - javascript

my javascript gives a estimate for name plates
each letter is $10
Very new to Javascript, I am trying to get rid of the text Area on my input/display once the submit/button is clicked. . . . lets just say if I want to re-enter an input it should clear the last input and give new price . . . right now is piling up
for example : Enter Name: Total Cost is $30Total Cost is $60Total Cost is $60Total Cost is $90Total Cost is $110Total Cost is $140
<body>
<div id='container' >
<div id='banner'>
<h4 id='signName'>Name Plate Estimate</h4>
</div>
<p id="enterName">Enter Name: </p>
<div id='form'>
<form>
<input id="userInput" name="userInput" type="text" />
<br>
</form>
</div>
<button id="button">Show Cost</button>
</div>
</body>
heres my javascript ;
document.getElementById('button').onfocus = function(){
var userText = document.getElementById('userInput').value ;
var cost = 10 ;
var price = function(){
var total = userText.length * cost;
return total ;
}
if (userText.length === 0){
var elError = document.getElementById('enterName') ;
elError.innerHTML += "Please enter a valid name" ;
} else {
var elErrror = document.getElementById('enterName') ;
elErrror.innerHTML += 'Total Cost is $' + price() ;
}
}

You are appending the new data to your element with +=, you want to replace the whole innerHTML, so just use the = operator.
elErrror.innerHTML += 'Total Cost is $' + price() ;
becomes
elErrror.innerHTML = 'Total Cost is $' + price() ;

Please add below script:
document.getElementById('userInput').onfocus = function(){
document.getElementById('userInput').value = ''
};

Related

How to get values of multiple textboxes from a php loop and sum them using javascript

What i want is that every row should have its summation (row1=price x quantity) as the quantity changes the sum should be changing automatically(total=row1 + row2 +row3) so as the total of all rows.As it is am only able to achieve that with first row. Test my code here https://malawiclinic.000webhostapp.com/
<form class="form-inline">
<?php
$sqlm="SELECT * FROM tbl_wishlist ORDER BY id DESC ";
$resultmn=mysqli_query($db,$sqlm);
$fcount=mysqli_num_rows($resultmn);
if ($fcount>0) {
$countprice=0;
while($found = mysqli_fetch_array($resultmn)) {
$product = $found['product'];
$qty = $found['Quantity'];
$price = $found['price'];
echo "
<div class='form-group'>
<label for='exampleInputName2'>$product</label>
<input type='text' class='form-control' id='price'
value='$price'>
</div>
<div class='form-group'>
<input type='number' class='input-text form-control'
id='quantity' value='$qty'>
</div>
<label for='exampleInputName2'>$
<span id='result'></span>
</label>";
}
} ?>
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on("input",".input-text", function(){
var x = document.getElementById("quantity").value;
var x1 = document.getElementById("price").value;
var total = x1 * x;
var totals = total.toLocaleString(undefined,
{maximumFractionDigits:2});
$("#result").html(totals);
$("#totals").html(totals);
});
});
</script>
First of all, the id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document). You have three fields with id="price", three with id="quantity" and three with id="result" which is not valid, so you should remove those id(s).
Now, you will have to access these fields using their class names by getElementsByClassName. Since, all the fields have form-control as their common class, this code below will do the job. And also replace all id="result" with class="result".
$(document).ready(function(){
var input = document.getElementsByClassName('form-control');
var result = document.getElementsByClassName('result');
var total = 0;
for(var i=0; i<input.length; i+=2){
var product = input[i].value * input[i+1].value;
total += product;
product = product.toLocaleString(undefined, {maximumFractionDigits:2});
result[i/2].innerHTML = product;
}
total = total.toLocaleString(undefined, {maximumFractionDigits:2});
$("#totals").html(total);
});

I need to remove an object from an array and display a message upon conditions

I need a user to input 2 objects in the array. If a duplicate entry is found on the number of the flight, an alert should happen. The issue is, that the alert prevents a user from entering a certain input BUT it still adds both inputs to the array even after the alert, causing the total number of miles to be wrong. The duplicate doesn't show up in the table which is good.
Upon submission of another button, the user's level is supposed to be displayed but it displays nothing. I don't know if its because of the first issue or not.
I have tried to use pop() and splice() and it produced more errors.
var total = 0;
const flightTable = document.getElementById('flightTable'),
button = document.getElementById('display'),
flightNum = document.getElementById('flightNumber'),
milesFlown = document.getElementById('milesFlown'),
addRow = () => {
const tr = document.createElement('tr'),
tdFlightNo = document.createElement('td'),
tdMilesFlown = document.createElement('td');
tdMilesFlown.setAttribute('class', 'needsToBeCounted');
/** getting the last record in the flight objects array **/
tdFlightNo.textContent = flightArray[i - 1].flightNumber;
tdMilesFlown.textContent = flightArray[i - 1].milesFlown;
/** append the TDs elements to the TR element (all of them are created above dynamically) **/
tr.append(tdFlightNo, tdMilesFlown);
/** append that row to the HTML table **/
flightTable.appendChild(tr);
}
let flightArray = [],
flightNumValue = null,
milesFlownValue = null,
i = 0;
button.addEventListener('click', () => {
flightNumValue = flightNum.value;
milesFlownValue = milesFlown.value;
/** checking for duplicate entry **/
if (flightArray.find(el => {
return el.flightNumber === flightNumValue
})) {
alert('You cannot enter this flight due to Duplicate Flight Number entry: "' + flightNumValue + '"');
return false;
}
/** add the entry in the flight objects table **/
flightArray[i++] = {
flightNumber: flightNumValue,
milesFlown: milesFlownValue
}; /** add the flight record to the array and increment the counter i (notice the i++) **/
addRow(); /** call addRow to add a new row in the table (HTML) **/
});
function getClassStatus() {
var cls = document.getElementById("flightTable").getElementsByTagName("td");
for (var i = 0; i < cls.length; i++) {
if (cls[i].className == "needsToBeCounted") {
total += isNaN(cls[i].innerHTML) ? 0 : parseInt(cls[i].innerHTML);
}
console.log(total);
//document.getElementById("classMessages").innerHTML = total +" miles";
document.getElementById("classMessages").innerHTML = "is the total amount of miles you have flown";
document.getElementById("totalNoOfMiles").value = Number(total);
console.log(total);
displayMessage();
}
function displayMessage() {
var totalValue = document.getElementsByName('totalNoOfMiles');
var bMessageTag = document.getElementById("bMessage");
var sMessageTag = document.getElementById("gMessage")
var gMessageTag = document.getElementById("sMessage");
if (totalValue < 10000) {
bMessageTag.innerHTML = "You are a Bronze member."
document.getElementById('sMessage').innerHTML = "";
document.getElementById('gMessage').innerHTML = "";
console.log(bMessageTag);
}
if (totalValue >= 10000 && total <= 24999) {
sMessageTag.innerHTML = "You are a Silver member."
document.getElementById('gMessage').innerHTML = "";
document.getElementById('sMessage').innerHTML = "";
}
if (totalValue > 25000) {
gMessageTag.innerHTML = "You are a Gold member."
document.getElementById('sMessage').innerHTML = "";
document.getElementById('bMessage').innerHTML = "";
}
}
}
<form name="attention">
<label>Please enter your flight Number:</label><br>
<input type="text" id="flightNumber" name="flightnumber" value="" />
<br />
<label>Please enter Miles Flown:</label><br>
<input type="text" id="milesFlown" name="milesflown" value="" />
<br>
<input type="button" id="display" name="display" value="Submit Flight Information" />
<br>
<input type="button" id="status" name="status" value="Get Class Level" onclick=getClassStatus(); />
<br>
<input type="number" id="totalNoOfMiles" name="totalNoOfMiles" value="" />
<div id="classMessages"></div>
<h3>Your Passenger Class Level is:</h3>
<div id="bMessage"></div>
<div id="sMessage"></div>
<div id="gMessage"></div>
<table id="flightTable">
<tr>
<th>Flight Number</th>
<th>Number of Miles</th>
</tr>
</table>
</form>
When a user enters in two inputs, the inputs should be displayed in a table after clicking a button to submit the info. For a user to get its' "level" they should click another button. Their level displays based on the sum of one of their inputs(miles). The levels should change dynamically depending on their level. A duplicate entry on flight # can not be accepted.
You total accumulator is always appending to the total so the total number of miles will forever grow.
Your messages are not displaying because values stored from type="text" inputs will always be a string where later you compare string to number. Strings are compared character by character until they are not equal or there aren't any characters left to compare. What you need is numeric comparison so number < number is a more accurate expression for your logic.
Let's get to it...
When a user adds flight information we can acquire both flight no. and miles. We want to save the miles as a numeric value as such:
milesFlownValue = Number(milesFlown.value);
Instead of declaring an iterator, you could push each object to flightArray...
flightArray.push({
flightNumber: flightNumValue,
milesFlown: milesFlownValue
});
You can then use the size of this array to a) check if the array has any elements to execute logic on and b) if so, you can execute tests using Array.prototype.some which works great for conditional statements. Notice in the below conditional that toLowerCase() is vital because you'll want flight numbers like A123 and a123 to be the same thing.
if (flightArray.length &&
flightArray.some(entry => entry.flightNumber.toLowerCase() === flightNumValue.toLowerCase()) ) {
...
}
Now when you add a new row, there's no pop() or slice() needed because you're not wanting to change the state of the original array. You can simply get the last item the traditional way...
lastItem = flightArray[flightArray.length - 1]
The rest is pretty straight forward but I've improved some code that I'm hoping you'll benefit from.
const flightTable = document.getElementById('flightTable'),
button = document.getElementById('display'),
flightNum = document.getElementById('flightNumber'),
milesFlown = document.getElementById('milesFlown'),
status = document.getElementById('status'),
classLevel = document.getElementById("classLevel");
const addRow = () => {
const tr = document.createElement('tr'),
tdFlightNo = document.createElement('td'),
tdMilesFlown = document.createElement('td'),
lastItem = flightArray[flightArray.length - 1];
tdFlightNo.textContent = lastItem.flightNumber;
tdMilesFlown.textContent = lastItem.milesFlown;
tr.append(tdFlightNo, tdMilesFlown);
flightTable.appendChild(tr);
}
let flightArray = [],
flightNumValue = null,
milesFlownValue = null,
total = 0;
button.addEventListener('click', () => {
flightNumValue = flightNum.value;
milesFlownValue = Number(milesFlown.value);
if (flightArray.length && flightArray.some(entry => entry.flightNumber.toLowerCase() === flightNumValue.toLowerCase())) {
alert('You cannot enter this flight due to Duplicate Flight Number entry: "' + flightNumValue + '"');
return false;
}
flightArray.push({
flightNumber: flightNumValue,
milesFlown: milesFlownValue
});
addRow();
});
status.addEventListener('click', () => {
total = flightArray.reduce((a, b) => a + b.milesFlown, 0)
document.getElementById("classMessages").innerHTML = `${total} is the total amount of miles you have flown`;
displayMessage();
})
function displayMessage() {
let output = "";
if (total > 0 && total < 10000) {
output = "You are a Bronze member.";
}
else if (total >= 10000 && total <= 24999) {
output = "You are a Silver member.";
}
else if (total > 25000) {
output = "You are a Gold member.";
}
classLevel.textContent = output;
}
<form name="attention">
<label>Please enter your flight Number:</label>
<br />
<input type="text" id="flightNumber" name="flightnumber" value="" />
<br />
<label>Please enter Miles Flown:</label>
<br />
<input type="text" id="milesFlown" name="milesflown" value="" />
<br />
<input type="button" id="display" name="display" value="Submit Flight Information" />
<br />
<input type="button" id="status" name="status" value="Get Class Level" />
<br />
<br />
<div id="classMessages"></div>
<div id="classLevel"></div>
<br />
<table id="flightTable">
<tr>
<th>Flight Number</th>
<th>Number of Miles</th>
</tr>
</table>
</form>

There's a simple logic error in my JS that I lack the knowledge to find

<!DOCTYPE html>
<html>
<head>
<title>
Unit 2 Graded Exercise 1
</title>
</head>
<body>
<header>
<h1>Unit 2 Graded Exercise 1</h1>
<br/>
</header>
<form>
<fieldset>
<label for="price" id="label">Purchase Price</label>
<input type="text" id="partPrice" />
<button type="button" id="button">Calculate Shipping and Handling</button>
</fieldset>
</form>
</body>
<script>
var partPrice = document.getElementById("partPrice").value;
var totalPrice;
function calcTotal() {
if (partPrice <= 25) {
var totalPrice = partPrice + 1.5; //price + sh
} else if (partPrice > 25) {
var totalPrice = (partPrice * 0.10) + partPrice; //10% of price as sh + price
}
alert("Shipping and Handling is $" + totalPrice);
}
var submitButton = document.getElementById("button");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", calcTotal, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", calcTotal);
}
</script>
</html>
So my goal is to show interest + $1.50 for a total cost below or equal to $25 and 10% interest of a total cost above $25. My problem is that the "partPrice", which is the price that the user enters, is not being received. I've looked up quite a bit about this and I've seen people go around by creating multiple variables to pick up certain values but I have yet to understand why. I would really like an explanation because, going through this code, it all looks logically correct. I'm really lost as to where I should be changing my syntax.
Update your code to following
Move the get value code inside the function
Convert the value which is a string to a number
function calcTotal() {
var partPrice = parseFloat(document.getElementById("partPrice").value);
...
}
Just get data inside function. also remove variable declaration in if statement
<html>
<head>
<title>
Unit 2 Graded Exercise 1
</title>
</head>
<body>
<header>
<h1>Unit 2 Graded Exercise 1</h1>
<br/>
</header>
<form>
<fieldset>
<label for="price" id="label">Purchase Price</label>
<input type="text" id="partPrice" />
<button type="button" id="button">Calculate Shipping and Handling</button>
</fieldset>
</form>
</body>
<script>
var partPrice,
totalPrice;
function calcTotal() {
partPrice = document.getElementById("partPrice").value;
if (partPrice <= 25) {
totalPrice = partPrice + 1.5; //price + sh
} else if (partPrice > 25) {
totalPrice = (partPrice * 0.10) + partPrice; //10% of price as sh + price
}
alert("Shipping and Handling is $" + totalPrice);
}
var submitButton = document.getElementById("button");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", calcTotal, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", calcTotal);
}
</script>
</html>
var partPrice = document.getElementById("partPrice").value;
This line is executed once when the script is loaded, so partPrice will be an empty string. It doesn't get reevaluated automatically when you write anything in input, so you'll have to call document.getElementById("partPrice").value again in calcTotal to fetch the current value of partPrice.

How To Get Multiple Outputs to Show From a For Loop

I have a for loop to get multiple outputs from an array. The currencyType[type] is used to pre-pend the proper letters to match the DIV ID in the HTML.
for(let type = 0; type <= currencyType.length; type++) {
// This grabs the number from XRPUSDVAL + XRPUSDAMT
let node = document.getElementById(currencyType[type].innerHTML+"USDVAL").textContent * document.getElementById(currencyType[type].innerHTML+"USDAMT").value;
let total = node.toFixed(2);
console.log(total)
}
I get 2 values of the total inside my console with the statement above that are dynamic numbers.
65704.50
99.91
However when I add a statement to try to output it to a DIV ID on my HTML, The console then only shows the result of 1 of the outputs
for(let type = 0; type <= currencyType.length; type++) {
// This grabs the number from XRPUSDVAL + XRPUSDAMT
let node = document.getElementById(currencyType[type].innerHTML+"USDVAL").textContent * document.getElementById(currencyType[type].innerHTML+"USDAMT").value;
let total = node.toFixed(2);
console.log(total)
document.getElementById(currencyType[type]+"USDTOTAL").innerHTML = total; // <------ Added This Statement
}
Here is the section of the HTML as well where the Javascript interacts with
<div class="container">
<div class="row">
<div class="col-sm-4 pbf-crypto-container">
<form method="POST" action="/users/currencies/68">
<h3 class="pbfCurrencyType">ETH</h3>
<input class="form-control-lg" id="ETHUSDAMT" name="amount" type="text" value="75">
<h3>Market Value: ($)</h3>
<div id="ETHUSDVAL"></div>
<h3>Total Value: ($)</h3>
<div id="ETHUSDTOTAL"></div>
<hr>
<input class="btn btn-primary" id="pbf-update" type="submit" value="Update">
<button class="btn btn-primary" id="pbf-refresh">Refresh</button>
</form>
</div>
<div class="col-sm-4 pbf-crypto-container">
<form method="POST" action="/users/currencies/60">
<h3 class="pbfCurrencyType">XRP</h3>
<input class="form-control-lg" id="XRPUSDAMT" name="amount" type="text" value="100">
<h3>Market Value: ($)</h3>
<div id="XRPUSDVAL"></div>
<h3>Total Value: ($)</h3>
<div id="XRPUSDTOTAL"></div>
<hr>
<input class="btn btn-primary" id="pbf-update" type="submit" value="Update">
<button class="btn btn-primary" id="pbf-refresh">Refresh</button>
</form>
</div>
</div>
</div>
I was wondering if someone can show me the proper way so that within my for loop it will be able to insert the total's into the section of my DIV that I specified. I am not sure what I am doing wrong here. Any help would be much appreciated. Thank you.
This line seems to be wrong
document.getElementById(currencyType[type]+"USDTOTAL").innerHTML = total;
You need to append USDTOTAL to currencyType[type].innerHTML like earlier in the same loop.
Make it
document.getElementById(currencyType[type].innerHTML +"USDTOTAL").innerHTML = total;
Or refactor the code
for(let type = 0; type <= currencyType.length; type++)
{
let prefix = currencyType[type].innerHTML ;
let node = document.getElementById( prefix +"USDVAL").textContent * document.getElementById( prefix +"USDAMT").value;
let total = node.toFixed(2);
console.log(total)
document.getElementById( prefix + "USDTOTAL").innerHTML = total;
}
try to append the results:
for(let type = 0; type <= currencyType.length; type++) {
// This grabs the number from XRPUSDVAL + XRPUSDAMT
let node = document.getElementById(currencyType[type].innerHTML+"USDVAL").textContent * document.getElementById(currencyType[type].innerHTML+"USDAMT").value;
let total = node.toFixed(2);
console.log(total)
document.getElementById(currencyType[type]+"USDTOTAL").innerHTML += total; // <------ Added This Statement
}
I think that you can improve a lite bit more you code
from here:
for(let type = 0; type <= currencyType.length; type++)
{
let prefix = currencyType[type].innerHTML ;
let node = document.getElementById( prefix +"USDVAL").textContent * document.getElementById( prefix +"USDAMT").value;
let total = node.toFixed(2);
console.log(total)
document.getElementById( prefix + "USDTOTAL").innerHTML = total;
}
to here:
currencyType.forEach(currency => {
const prefix = currency.innerHTML;
const node = document.getElementById(`${prefix}USDVAL`).textContent * document.getElementById(`${prefix}USDAMT`).value;
const total = node.toFixed(2);
document.getElementById(`${prefix}USDTOTAL`).innerHTML = total;
});

Sales and tip calculator

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;

Categories