I am new to javaScript.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
<style>
body { "background-color: #fff; color: #000; font-size: 14px;
position: relative;}
form {
font-size:16px;
}
</style>
</head>
<!-- Embedded css style -->
<body>
<div>
<header>
<h1>Example</h1>
</header>
<div class= "container">
<main>
<form>
<fieldset>
<legend>
Example
</legend>
<!--asks for name-->
<label for="nameInput">Name</label>
<input type="text" id="nameInput" name="name" placeholder="John Doe" />
<br>
<!--asks for purchase price -->
<label for="amt">Amount:</label>
<input type="text" id="amt"><br>
<!--asks for state-->
<input type="radio" name="stateCode" value="k" id="k" checked> Kansas
<input type="radio" name="stateCode" value="c" id="c"> California
<input type="radio" name="stateCode" value="m" id="m">Missouri
<br>
<label for="tax">Tax :</label>
<input type="text" id="tax" disabled><br>
<label for="totalCost">Your total is:</label>
<input type="text" id="totalCost" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</fieldset>
</form>
</main>
</div><!-- end .container -->
</div><!--end of #pushDown -->
</body>
</html>
javascript:
// returns a html element (id)
var $ = function(id) {
return document.getElementById(id);
};
// calculates total after sales tax
function coffeeCalc(amt,tax) {
var totalCost = amt + tax;
totalCost = totalCost.toFixed(2); // 2 decimals
return totalCost; // returns value
}
function init() {
// assign variables to id and class values from HTML page
var amt = parseFloat( $("amt").value);
// declaring variables
var taxRate;
var stateSelected; // for console log purpose only
// radio buttons
if ($("k").checked) {
taxRate = .087; // tax rate: 8.7%
stateSelected = "Kansas";
} else if ($("c").checked) {
taxRate = .077; // tax rate: 7.7%
stateSelected = "California";
} else {
taxRate = .09; // tax rate: 9%
stateSelected = "Missouri";
}
var tax = amt * taxRate;
// shows output
$("tax").value = tax.toFixed(2); // 2 decimals
$("totalCost").value = coffeeCalc(amt,tax); //calls the coffeeCalc function
}
Image 1:
On the bottom right side: it shows totalCost: input#totalCost. The debugger displays amt: 10, so therefore I would think it would resemble amt except it should be:
total: 10.87.
Image 2: After I finish debugging the last line:
console.log(“Total Cost: “ + $(“totalCost).value);
it opens a new tab: VM236 with amt
What does that mean?
The variable totalCost in your screenshot refers to the DOM element, not the value from the coffeeCalc function, since that has already completed by the time your breakpoint has been reached (and the totalCost variable is locally scoped to that function).
You can see by typing totalCost into the console (without having broken) that there is a globally-scoped variable called totalCost, the value of which is the input element. (See screenshot here)
Regarding the new tab, the debugger is simply continuing to step through code that's running. VM... files are generated by Chrome's Dev Tools for scripts that have no sourceURL (that have been injected dynamically).
You say you are new to JS, so if you haven't already, you might want to take a look Chrome's official 'Getting Started' guide to debugging.
Related
I've looked over a number of threads here of similar problems to little avail - I can't figure out exactly what's going wrong here. Google claims that the element I'm trying to reference is null
Uncaught TypeError: Cannot read property 'addEventListener' of null at sales.js:12
and no matter how I've tried to fix it, it doesn't seem to work. As you can see in the js code, I've tried a number of ways of fixing it based on stuff I've found here.
Originally the <script src ="sales.js"> in the HTML file was up in the head, but I read in some pages here that putting it there can make it load before everything else and to put it down before the HTML closing tag.
Any suggestions?
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<main>
<h1>Sales Calculator</h1>
<p>Complete the form and click "Calculate".</p>
<fieldset>
<legend>
Item Information
</legend>
<label for="item">Item:</label>
<input type="text" id="item" ><br>
<label for="price">Price:</label>
<input type="text" id="price" ><br>
<label for="discount">Discount %:</label>
<input type="text" id="discount" ><br>
<label for="taxRate">Tax Rate:</label>
<input type="text" id="taxRate" ><br>
<label for="total">Discount Price:</label>
<input type="text" id="discountPrice" disabled ><br>
<label for="salesTax">Sales Tax:</label>
<input type="text" id="salesTax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br><br>
<div id="buttons">
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br></div>
</fieldset>
<pre>© Fall 2020 Rob Honomichl - Dakota State University</pre>
</main>
</body>
<script src="sales.js"></script>
</html>
JS Code:
//"use strict"
var $ = function (id) {
return document.getElementById(id);
};
//window.addEventListener("DOMContentLoaded", () => {
//$("#calculate").addEventListener("click", processEntries);
//});
window.addEventListener('DOMContentLoaded', function () {
document.getElementById("#calculate").addEventListener("click", processEntries);
});
//window.onload = function(){
//$("#calculate").addEventListener("click", processEntries);
//};
const processEntries = () => {
//Gather User Input
//var item = document.querySelector("#item").value;
var price = parseFloat(document.querySelector("#price").value).toFixed(2);
var discount = parseInt(document.querySelector("#discount").value);
var taxRate = parseInt(document.querySelector("#taxRate").value);
//Calculate Discounted Price
function discountPriceCalc(price, discount) {
const disPrice = price * (discount/100);
return disPrice.toFixed(2);
}
//Calculate Sales Tax
function salesTaxCalc(discountPrice, taxRate) {
const taxTotal = price * (taxRate/100);
return taxTotal.toFixed(2);
}
//Calculate Total
function totalCalc(discountPrice, salesTax) {
return ((Number(discountPrice) + Number(salesTax).toFixed(2)));
}
//Calculate the disabled text box values
var discountPrice = discountPriceCalc(price, discount);
var salesTax = salesTaxCalc(discountPrice, taxRate);
var Total = totalCalc(discountPrice, salesTax);
//Update Text Boxes
document.getElementById("discountPrice").value = discountPrice;
document.getElementById("salesTax").value = salesTax;
document.getElementById("total").value = Total;
//set focus to Item box after
document.getElementById("item").focus();
};
You need to get rid of the # in the getElementById call to properly locate the element.
window.addEventListener('DOMContentLoaded', function () {
document.getElementById("calculate").addEventListener("click", processEntries);
});
I am trying to create a simple form that when a user enters the number of respective, countries, states or cities that one has visited it displays that sum. The form resets as desired upon the page being reloaded, however I am not seeing the placesTraveled element being displayed. Am I overlooking a typo or missing an essential element?
HTML Snippet:
<article>
<h3>Oh the places you have gone</h3>
<p>This past year has been tough for those who love to travel, as a reminder to ourselves<br>
of the places we have already been, fill in the form below to see all the places you have been</p>
<form id="placesTraveledForm">
<fieldset>
<legend><span>Places Traveled</span></legend>
<input class="input p-section p-border" type="number" min="1" max="195" id="countries" value="1" />
<label for="countries">
<p># of countries visited (1‑195)</p>
</label>
<input class="input p-section p-border" type="number" min="1" id="states" value="1" />
<label for="states">
<p># states, territories, or provinces visited </p>
</label>
<input class="input p-section p-border" type="number" min="1" id="cities" value="1" />
<label for="cities">
<p># cities, hamlets, or towns visited </p>
</label>
</fieldset>
</form>
</article>
<aside>
<p>Number of Places Traveled To:
<span id="placesTraveled">
</span>
</p>
</aside>
</div>
JavaScript Snippet:
//global variables
var totalNumber = 0;
// calculates places visted based upon user entry
function calcPlaces() {
var con = document.getElementById("countries");
var st = document.getElementById("states");
var cty = document.getElementById("cities");
totalNumber = con.value + st.value + cty.value;
document.getElementById("placesTraveled").innerHTML = totalNumber;
}
// sets all form field values to defaults
function resetForm() {
document.getElementById("countries").value =1;
document.getElementById("states").value =1;
document.getElementById("cities").value =1;
calcPlaces();
createEventListeners();
}
//create event listeners
function createEventListeners () {
document.getElementById("countries").addEventListener("change", calcStaff, false);
document.getElementById("states").addEventListener("change", calcStaff, false);
document.getElementById("cities").addEventListener("change", calcStaff, false);
}
//resets form when page is reloaded
document.addEventListener("load", resetForm, false);
createEventListeners()```
the code mentioned totalNumber = con.value + st.value + cty.value;
They are actually strings, not numbers. The easiest way to produce a number from a string is to prepend it with replace this line with
totalNumber = +con.value + +st.value + +cty.value;
calcStaff is not a function actual name of your function is calcPlaces
<html><div>
<article>
<h3>Oh the places you have gone</h3>
<p>This past year has been tough for those who love to travel, as a reminder to ourselves<br>
of the places we have already been, fill in the form below to see all the places you have been</p>
<form id="placesTraveledForm">
<fieldset>
<legend><span>Places Traveled</span></legend>
<input class="input p-section p-border" type="number" min="1" max="195" id="countries" value="1" />
<label for="countries">
<p># of countries visited (1‑195)</p>
</label>
<input class="input p-section p-border" type="number" min="1" id="states" value="1" />
<label for="states">
<p># states, territories, or provinces visited </p>
</label>
<input class="input p-section p-border" type="number" min="1" id="cities" value="1" />
<label for="cities">
<p># cities, hamlets, or towns visited </p>
</label>
</fieldset>
</form>
</article>
<aside>
<p>Number of Places Traveled To:
<span id="placesTraveled">
</span>
</p>
</aside>
</div>
<script>
var totalNumber = 0;
// calculates places visted based upon user entry
function calcPlaces() {
var con = document.getElementById("countries");
var st = document.getElementById("states");
var cty = document.getElementById("cities");
totalNumber = +con.value + +st.value + +cty.value;
document.getElementById("placesTraveled").innerHTML = totalNumber;
}
// sets all form field values to defaults
function resetForm() {
document.getElementById("countries").value =1;
document.getElementById("states").value =1;
document.getElementById("cities").value =1;
calcPlaces();
createEventListeners();
}
//create event listeners
function createEventListeners () {
document.getElementById("countries").addEventListener("change", calcPlaces, false);
document.getElementById("states").addEventListener("change", calcPlaces, false);
document.getElementById("cities").addEventListener("change", calcPlaces, false);
}
//resets form when page is reloaded
document.addEventListener("load", resetForm, false);
createEventListeners()
</script>
</html>
When I run the code on my chrome browser, clicking the calculate button, it does not put the value in the Total and Sales Tax text box.
Also "Add the Javascript event handler for the click event of the Clear button, This should clear all text boxes and move the cursor to the Subtotal field."
I'm using Html and js file. Using a function expression to calculate and display my calculation, then also use the clear button to clear all text boxes.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="sales_tax.js"></script>
</head>
<body>
<main>
<h1>Sales Tax Calculator</h1>
<p>Enter Subtotal and Tax Rate and click "Calculate".</p>
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" ><br>
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" ><br>
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br>
</main>
</body>
</html>
This is my js file.
var $ = function (id) {
return document.getElementById(id);
};
var SumSalesTax = function (sub, rate){
var sales_tax = (sub * rate);
sales_tax = sales_tax.toFixed(2);
var total = (sub * rate + sub);
total = total.toFixed(2);
return sales_tax, total;
}
var processEntries = function() {
var sub = parseFloat($("subtotal").value);
var rate = parseFloat($("tax_rate").value);
if (sub < 0 && sub > 10000 && rate < 0 && rate > 12) {
alert("Subtotal must be > 0 and < 1000, and Tax Rate must be >0 and < 12.
")
} else {
$("sales_tax").value = SumSalesTax(sub, rate);
$("total").value = SumSalesTax(sub, rate);
}
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("clear").onclick = sumSalesTax;
};
Sales Tax Calculator
It seems like you had a typo when you were doing $("clear").onclick = sumSalesTax;, as the variable was named SumSalesTax rather than with the lower case. This meant that the code block errored out and therefore didn't actually run. Make sure you make good use of the browser console so you can spot errors like this! The below example should work
var $ = function (id) {
return document.getElementById(id);
};
var SumSalesTax = function (sub, rate){
var sales_tax = (sub * rate);
sales_tax = sales_tax.toFixed(2);
var total = (sub * rate + sub);
total = total.toFixed(2);
return sales_tax, total;
}
var processEntries = function() {
var sub = parseFloat($("subtotal").value);
var rate = parseFloat($("tax_rate").value);
if (sub < 0 && sub > 10000 && rate < 0 && rate > 12) {
alert("Subtotal must be > 0 and < 1000, and Tax Rate must be >0 and < 12.")
} else {
$("sales_tax").value = SumSalesTax(sub, rate);
$("total").value = SumSalesTax(sub, rate);
}
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("clear").onclick = SumSalesTax;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="sales_tax.js"></script>
</head>
<body>
<main>
<h1>Sales Tax Calculator</h1>
<p>Enter Subtotal and Tax Rate and click "Calculate".</p>
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" ><br>
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" ><br>
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br>
</main>
</body>
</html>
I tried to make a function by passing an event to a button but it is not working. What I want the function to do is that when the button is clicked show in the DOM that I click and also display with the innerhtml a message on the web page using if/ else depending of the user imput in the imputs of time abd weight
$(document).ready(function() {
$('#calculate').on('click', function() {
$('#calculate ul li input').slideToggle(800);
});
/********************************************************/
var gender = $('#gender');
var age = $('#age');
var time = $('#time');
var weigth = $('#weight');
var result = $('#result');
var calculate = $('#calculate');
if (calculate.lenght) {
/*event listener*/
calculate.on('click', calculateF);
/*para que cuando se haga click se active la funcion calcular
que estoy creando abajo*/
function calculateF(event) {
event.preventDefault();
console.log("click");
var timeVal = parseInt(time.val());
var weightVal = parseInt(weight.val());
if (time > 8 && weight > 25) {
result.html(" text ");
} else {
result.html("text");
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="manejo_cargas" id="manejo_cargas">
<h3>calculate work load</h3>
</div>
<section id="calculate">
<div class="calculate">
<ul>
<li><input type="text" name="text" placeholder="Gender" id="gender"></li>
<li><input type="number" name="number" placeholder="age" id="age"></li>
<li><input type="number" name="number" placeholder="time" id="time"></li>
<li><input type="number" name="number" placeholder="weight" id="weight"></li>
</ul>
</div>
</section>
<div class="calculate">
<input type="button" class="button" value="result" id="calculate">
</div>
<!--here comes the result-->
<div class="result" id="result">
</div>
.
You are missing the # if you have declared the time, weight, result, and calculate as id's of the elements that you are targeting.
From what I can guess is that the weight and time are inputs the result is a div and the calculate is the button to be clicked.
I will assume they are ids so you need to add # before the id when specifying selectors in jquery using $() otherwise use . if they are class names.
Then if you are converting the code to jquery from javascript you need to replace the respective functions like addEventListener .innerHtml , .value etc
You can see the working below but the calculations and the message that you have to add is on your end as you never provided any details so i have made the conversion for the code
$(document).ready(function() {
var time = $('#time');
var weight = $('#weight');
var result = $('#result');
var calculate = $('#calculate');
/*event listener*/
calculate.on('click', calculateF);
function calculateF(event) {
event.preventDefault();
console.log("you hit click");
/*new variables*/
var timeVal = parseInt(time.val());
var weightVal = parseInt(weight.val());
if (time > 8 && weight > 25) {
result.html(" if condition true ").show();
} else {
result.html("message from the else part").show();
}
}
});
.result {
border: 1px solid #c7c7c7;
padding: 5px;
text-align: center;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!--here comes the result-->
<div class="result" id="result">
</div>
<div class="manejo_cargas" id="manejo_cargas">
<h3>calculate work load</h3>
</div>
<section>
<div class="calculate">
<ul>
<li><input type="text" name="text" placeholder="Gender" id="gender"></li>
<li><input type="number" name="number" placeholder="age" id="age"></li>
<li><input type="number" name="number" placeholder="time" id="time"></li>
<li><input type="number" name="number" placeholder="weight" id="weight"></li>
</ul>
</div>
</section>
<div class="calculate">
<input type="button" class="button" value="result" id="calculate">
</div>
<!--folder where my jquery code is saved-->
<script src="js/jquery.js"></script>
<!--folder where my jquery code is saved-->
<script src="js/scripts.js"></script>
EDIT
Your HTML has duplicate id calculate for the section and for the input button that's why it isn't working you cannot have multiple elements with the same id I have used your HTML and removed the id from the section tag, see the demo above
I was trying to make a content score as a class assignment.
Assume : (The user sees a URL and then select the checkboxes that are assigned to issues . Each issue is assigned a score in a array.)
Whats working :
Individual checks are registered with their respective scores being displayed
Whats not working :
Can someone help me to update the score ( as the user checks the checkbox or unchecks).
I am assuming in future if i want to increase the issues I will be able to do that since it is in an array. (am i right)
(my week 4 in JS)
//Set up an array with the respective score
var code = new Array();
code["v1"] = 1;
code["v2"] = 2;
code["v3"] = 3;
code["v4"] = 5;
// As the user selects the checkbox I want to keep on adding the score and as the user unchecks I want to recalculate and display.
function getvalueScore() {
var score = 0;
//Get a reference to the form
var theForm = document.forms["contentForm"];
//Get a reference to the score from the "ContentForm"
var contentScore = theForm.elements["contentScore"];
// loop through each check box
for (var i = 0; i < contentScore.length; i++) {
//if the radio button is checked
if (contentScore[i].checked) {
// I want to calculate and keep updating the score
score = code[contentScore[i].value];
}
}
//return score
return score;
}
function calculateTotal() {
//calculation for final score
var scoreCard = getvalueScore();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Your Content Score is " + scoreCard;
}
function hideTotal() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
<!DOCTYPE html>
<html>
<head>
<title>Content Score</title>
<meta charset="utf-8">
<script src="formcalculations.js"></script>
</head>
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="contentForm" onsubmit="return false;">
<div>
<div class="cont_order">
Content Score</br>
<label>Please select the issues you see on the page to calculate the content score</label>
</br>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v1" onclick="calculateTotal()" />No content value</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v2" onclick="calculateTotal()" />Mediocre content value</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v3" onclick="calculateTotal()" />Obsolete content</label>
<br/>
<label class='radiolabel'>
<input type="checkbox" name="contentScore" value="v4" onclick="calculateTotal()" />Irrelevant content</label>
<br/>
<br/>
<br/>
<div id="totalPrice"></div>
</div>
</div>
</form>
</div>
<!--End of wrap-->
</body>
</html>
In your code you assign last selected checkbox to score variable, so the only thing you need to do is to sum the scores with:
score += code[contentScore[i].value];