This is my first time dealing with HTML and javascript, so pardon this simple question. I am trying to calculate the cost total cost of the fruits that the user wants to purchase. It was working fine earlier on but somehow it stopped working. May I know what is wrong here?
<!DOCTYPE html>
<html>
<head>
<title>My Title</title>
</head>
<body>
<form name="orderForm" action="orderProcess.php" onsubmit="return validateForm()" method="post">
<h1>My header</h1>
<label>User Name: </label>
<input type="text" name="username"> <br>
<label>Number of Apples ($0.69 / ea): </label>
<input type="text" name="AppleQty" id="AppleQty" oninput="calculateCost()"> <br>
<label>Number of Oranges ($0.59 / ea): </label>
<input type="text" name="OrangeQty" id="OrangeQty" oninput="calculateCost()"> <br>
<label>Number of Bananas ($0.39 / ea): </label>
<input type="text" name="BananaQty" id="BananaQty" oninput="calculateCost()"> <br>
<label>Total Cost: $</label>
<input type="text" name="totalCost" id="totalCost" readonly> <br>
</body>
<script type="text/javascript">
function calculateCost()
{
var appleQty = document.getElementById("AppleQty");
var orangeQty = document.getElementById("OrangeQty");
var bananaQty = document.getElementById("BananaQty");
if(isNaN(appleQty.value))
{
alert('Only Numeric Values Allowed');
appleQty.value = '';
appleQty.focus();
return false;
}
else if(isNaN(bananaQty.value))
{
alert('Only Numeric Values Allowed');
bananaQty.value = '';
bananaQty.focus();
return false;
}
else if(isNaN(orangeQty.value))
{
alert('Only Numeric Values Allowed');
orangeQty.value = '';
orangeQty.focus();
return false;
}
else
{
document.getElementById("totalCost").value = (appleQty.value * 0.69 + orangeQty.value * 0.59 + bananaQty.value * 0.39).toFixed(2);
}
}
</script>
Related
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="Author" content="Micah Cave">
<title>Ice 11</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#convert").click( function() {
var dollarAmount = $('input:text').val();
if ( $("#usa").is(':checked') )
dollarAmount = dollarAmount*1;
if ( $("#russia").is(':checked') )
dollarAmount = dollarAmount * 73.18;
});
});
</script>
</head>
<body>
<h1>Cave</h1>
<h2>Part 1B</h2>
<p>Type in the starting amount (in US dollars) here: <input type="text"></p>
<input type="checkbox" id="usa">US Dollars <br>
<input type="checkbox" id="russia">Russian Ruble <br>
<input type="checkbox" id="france">France Francs <br>
<input type="checkbox" id="japan">Japanese Yen <br>
<input type="button" id="convert" value="Convert currency(s)">
<p id="pasteHere"></p>
</body>
</html>
So I need to take the value that's entered in the input box above, and then if they check off any box(s) to then convert each checked boxs currency from US to whatever was selected, and then print out the results each time using if statements.
you can make a function called convert,when convert button click or checkbox click then call that function.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="Author" content="Micah Cave">
<title>Ice 11</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#convert").click(convert);
$("input:checkbox").click(convert)
});
function convert(){
var dollarAmount = $('input:text').val();
var result = " "
if ( $("#usa").is(':checked') )
result += dollarAmount*1 + ";";
if ( $("#russia").is(':checked') )
result += dollarAmount * 73.18 + ";";
$("#pasteHere").text(result)
}
</script>
</head>
<body>
<h1>Cave</h1>
<h2>Part 1B</h2>
<p>Type in the starting amount (in US dollars) here: <input type="text"></p>
<input type="checkbox" id="usa">US Dollars <br>
<input type="checkbox" id="russia">Russian Ruble <br>
<input type="checkbox" id="france">France Francs <br>
<input type="checkbox" id="japan">Japanese Yen <br>
<input type="button" id="convert" value="Convert currency(s)">
<p id="pasteHere"></p>
</body>
</html>
That is my solution:
$(document).ready(function() {
let selectedCurrencies = [];
$("#convert").click(function() {
let dollarAmount = $('input:text').val();
let checkBoxList = $('input:checked');
let resultText = "";
for (let i = 0; i < checkBoxList.length; i++) {
resultText += "US "+dollarAmount+" dollar =";
switch (checkBoxList[i].id) {
case 'usa':
resultText += dollarAmount * 1;
break;
case "russia":
resultText += dollarAmount * 73.18;
break;
}
resultText+=" "+(checkBoxList[i].nextSibling.textContent)+"<br>";
}
$("#pasteHere").html(resultText);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Cave</h1>
<h2>Part 1B</h2>
<p>Type in the starting amount (in US dollars) here: <input type="text"></p>
<input type="checkbox" id="usa">US Dollars <br>
<input type="checkbox" id="russia">Russian Ruble <br>
<input type="checkbox" id="france">France Francs <br>
<input type="checkbox" id="japan">Japanese Yen <br>
<input type="button" id="convert" value="Convert currency(s)">
<p id="pasteHere"></p>
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);
});
This is a problem for school. I need to make an array of records to store user input that loops the number of times the user specifies.
1 - The user will enter the number of volunteers (between 5-10). I have that part working.
2 - The input form is suppose to display the number of times as the number of volunteers. I'm not sure how to do that.
3 - The user's input is to be stored in an array of records.
4 - A message is to be displayed at the bottom with each volunteer's inputted information.
I'm stuck on number 2 and I'm positive I'll need help with 3 & 4 too.
Any assistance would be greatly appreciated.
You can see the code I've written below and I've included the JS code for both functions that I have working (validateForm() & getNumberOfVolunteers())
function getNumberOfVolunteers() {
var y = document.forms["numberOfVolunteersForm"]["numberOfVolunteers"].value;
if (y == "") {
alert("Number of volunteers must be filled out.");
return false;
}
document.getElementById("numberOfVolunteers1").innerHTML = y;
return false;
}
function validateForm() {
var a = document.forms["inviteForm"]["recipientName"].value;
if (a == "") {
alert("Name must be filled out.");
return false;
}
var b = document.forms["inviteForm"]["organizationName"].value;
if (b == "") {
alert("Organization name must be filled out.");
return false;
}
document.getElementById("recipientName1").textContent = a;
document.getElementById("organizationName1").textContent = b;
return false;
}
<!DOCTYPE html>
<html lang="en-US">
<!--
<head>
<script src="js/getNumberOfVolunteers.js"></script>
</head>
-->
<body>
<header>
</header>
<section id="numOfVolunteers">
<form name="numberOfVolunteersForm" onsubmit="return getNumberOfVolunteers()">
<label for="numberOfVolunteers">Number of volunteers:
</label>
<input type="number" min="5" max="10" value="5" name="numberOfVolunteers" id="numberOfVolunteers" placeholder="Enter the number of volunteers" />
<input type="submit" value="submit" id="submit1" />
</form>
</section>
<section id="pageForm">
<form action="#" name=inviteForm onsubmit="return getVolunteerInfoIntoArray()">
Number of Volunteers Entered: <strong><span id="numberOfVolunteers1"> </span></strong> <br/> <br/>
<label for="recipientName">Recipient name:
</label>
<input type="text" name="recipientName" id="recipientName" placeholder="Enter your Recipient Name" />
<label for="organizationName">Organization name:
</label>
<input type="text" name="organizationName" id="organizationName" placeholder="Enter your Organization Name" />
<input type="submit" value="submit" id="submit2" onclick="validateForm" />
</form>
</section>
<article id="placeholderContent">
Hello <span id="recipientName1"></span>!
<br/>
<br/> You have been invited to volunteer for an event held by <span id="organizationName1"></span>
</article>
<script>
var volunteerArray = [];
function getVolunteerInfoIntoArray() {
var volCount;
for (volCount = 5; volCount < getNumberOfVolunteers1.length; volCount++);
document.getElementById('recipientName');
document.getElementById('organizationName');
volunteerArray.push([recipientName.value, organizationName.value]);
}
</script>
</body>
</html>
I need to display the input form and the article multiple times. And store all the input in an array.
Is this what you're trying to do? Hope this helps even it's not exactly what you want hahahah
<!DOCTYPE html>
<html lang="en-US">
<head>
<style>
.numberofvolunteers,
.all-volunteers{
padding:10px;
}
input,button{
margin:3px;
}
span{
font-size:12px;
padding:10px 10px;
}
</style>
</head>
<body>
<div class="numberofvolunteers">
<input type="number" id="volunteers" placeholder="Enter No. of volunteers"><button onclick="createVolunteerForm()">Submit</button>
</div>
<div id="all-volunteers">
</div>
<span id="array"></span>
<script>
var volunteerArray = [];
function createVolunteerForm(){
volunteerArray = [];
var numberofvolunteers = document.getElementById("volunteers").value;
var content = "";
if(parseInt(numberofvolunteers) < 5 || parseInt(numberofvolunteers) > 10){
alert("No. of volunteer should be 5 to 10");
}
else{
for(var i = 0; i < parseInt(numberofvolunteers); i++){
content += createForm(i);
}
}
document.getElementById("all-volunteers").innerHTML = content;
}
function createForm(index){
var content = ' <div id="volunteer-div-'+index+'">'+
'<div id="volunteer-form-'+index+'">'+
'<input type="text" id=recipient-'+index+' placeholder="Enter recipient name">'+
'<input type="text" id=organization-'+index+' placeholder="Enter organization name">'+
'<button id="submit-'+index+'" onclick="displayMessage('+index+');addToArray('+index+');">submit</button>'+
'</div>'+
'<span id="message-'+index+'"></span>'+
'</div>';
return content;
}
function displayMessage(index){
var message = "Hello " + document.getElementById("recipient-"+index).value + " your organization is " + document.getElementById("organization-"+index).value;
document.getElementById("message-" + index).innerHTML = message;
}
function addToArray(index){
volunteerArray.push({recipient : document.getElementById("recipient-"+index).value , organization : document.getElementById("organization-"+index).value});
document.getElementById("array").innerHTML = JSON.stringify(volunteerArray);
}
</script>
</body>
</html>
A user is allowed to enter information in 5 input boxes.
I want the user to only be allowed to answer 3 questions from the form and as he answers the 3 questions of his choice the rest of the input text fields (boxes) in the form become disabled.
<html>
<h1>Security Questions</h1>
<body>
<p>
Only Enter Answer 3 Security Questions.
</p>
<form action="/submitAnswer.php" method="POST">
<label>What City Was Your Mom Born In?</label><br>
<input type="text" id="secQuestion01" name="secQuestion01"><br>
<label>What Is Your Dream Car?</label><br>
<input type="text" id="secQuestion02" name="secQuestion02"><br>
<label>What Is Your Mother's Maidan Name?</label><br>
<input type="text" name="secQuestion03"><br>
<label>What's Your Dream Job?</label><br>
<input type="text" name="secQuestion04"><br>
<label>Name Your First Grade Teacher?</label><br>
<input type="text" name="secQuestion05"><label><br>
<label>Name Your First Pet?</label><br>
<input type="text" name="secQuestion01"><label><br>
</form>
</body>
</html>
You can attach a keypress event listener to each of the inputs and increment a global variable when new input is added in other inputs. If the variable is equal to 3, disable all of the other inputs. If you want to allow the user to delete their answer to one question and answer another question, you will need to add a keydown event listener to each of the inputs and if the event's keyCode is 8 (backspace) and the current input's value's length is 1, then enable all of the other inputs.
<html>
<body>
<h1>Security Questions</h1>
<p>
Only Enter Answer 3 Security Questions.
</p>
<form action="/submitAnswer.php" method="POST" id="questionForm">
<label>What City Was Your Mom Born In?</label><br>
<input type="text" id="secQuestion01" name="secQuestion01"><br>
<label>What Is Your Dream Car?</label><br>
<input type="text" id="secQuestion02" name="secQuestion02"><br>
<label>What Is Your Mother's Maidan Name?</label><br>
<input type="text" name="secQuestion03"><br>
<label>What's Your Dream Job?</label><br>
<input type="text" name="secQuestion04"><br>
<label>Name Your First Grade Teacher?</label><br>
<input type="text" name="secQuestion05"><label><br>
<label>Name Your First Pet?</label><br>
<input type="text" name="secQuestion01"><label><br>
</form>
<script>
var inputs = document.querySelectorAll('#questionForm input');
var entered = [];
var numOfEntered = 0;
for(let i = 0; i < inputs.length; i++){
entered[i] = false;
inputs[i].addEventListener("keypress", function(e){
if(!entered[i]){
entered[i] = true;
numOfEntered++;
if(numOfEntered==3){
for(let j = 0; j < entered.length; j++){
if(!entered[j]){
inputs[j].disabled = true;
}
}
}
}
});
inputs[i].addEventListener("keydown", function(e){
if(e.keyCode==8&&this.value.length==1){
entered[i] = false;
numOfEntered--;
for(let z = 0; z < entered.length; z++){
inputs[z].disabled = false;
}
}
});
}
</script>
</body>
</html>
The following will accomplish what you need:
$(function () {
$('input').on('focusout', function () {
var $inputs = $('input');
var numAnswered = $inputs.filter(function () {
return $(this).val() !== '';
}).length;
$.each($inputs, function () {
if (numAnswered < 3) {
$(this).prop('disabled', false);
} else {
if (!$(this).val()) {
$(this).prop('disabled', true);
}
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<h1>Security Questions</h1>
<p>
Only Enter Answer 3 Security Questions.
</p>
<form action="/submitAnswer.php" method="POST">
<label>What City Was Your Mom Born In?</label><br>
<input type="text" id="secQuestion01" name="secQuestion01"><br>
<label>What Is Your Dream Car?</label><br>
<input type="text" id="secQuestion02" name="secQuestion02"><br>
<label>What Is Your Mother's Maidan Name?</label><br>
<input type="text" name="secQuestion03"><br>
<label>What's Your Dream Job?</label><br>
<input type="text" name="secQuestion04"><br>
<label>Name Your First Grade Teacher?</label><br>
<input type="text" name="secQuestion05"><label><br>
<label>Name Your First Pet?</label><br>
<input type="text" name="secQuestion01"><label><br>
</form>
</body>
</html>
I've been looking for 3 hours now for this error, and I can't for the life of me find it. It looks like the onsubmit isn't being called for whatever reason. I'm trying to make sure the user enters a non-negative number in each field
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validate(){
var wid1 = document.getElementByName("widget1").value;
var wid2 = document.getElementByName("widget2").value;
var wid3 = document.getElementByName("widget3").value;
if(isNaN(wid1)||isNaN(wid2)||isNaN(wid3)){
alert("all values entered must be numbers");
return false;
}
else if(wid1 < 0 || wid2 < 0 || wid3 < 0){
alert("all values must be greater than zero");
return false;
}
if(wid1+wid2+wid3 > 25){
if(!confirm("you have more than 25 items. Will you accept the additional shipping?")){
return false;
}
}
return true;
}
</script>
</head>
<body>
<form name="order" action="calculations.php" method="get" onsubmit="return validate()">
<p>37AX-L:</p>
<input type="text" name="widget1" value="0" required/>
<br>
<p>42XR-J</p>
<input type="text" name="widget2" value="0" required/>
<br>
<p>93XX-A</p>
<input type="text" name="widget3" value="0" required/>
<br>
<input type="radio" name="State" value="MO" checked>Missouri</input>
<br>
<input type="radio" name="State" value="IL">Illinois</input>
<br>
<input type="submit" value="submit"/>
</form>
</body>
</html>
First, the name of the function is getElementsByName -- Elements is plural.
Second, since this returns a NodeList, you need to index the result to access a specific element, so you can access its value.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validate(){
var wid1 = document.getElementsByName("widget1")[0].value;
var wid2 = document.getElementsByName("widget2")[0].value;
var wid3 = document.getElementsByName("widget3")[0].value;
if(isNaN(wid1)||isNaN(wid2)||isNaN(wid3)){
alert("all values entered must be numbers");
return false;
}
else if(wid1 < 0 || wid2 < 0 || wid3 < 0){
alert("all values must be greater than zero");
return false;
}
if(wid1+wid2+wid3 > 25){
if(!confirm("you have more than 25 items. Will you accept the additional shipping?")){
return false;
}
}
return true;
}
</script>
</head>
<body>
<form name="order" action="calculations.php" method="get" onsubmit="return validate()">
<p>37AX-L:</p>
<input type="text" name="widget1" value="0" required/>
<br>
<p>42XR-J</p>
<input type="text" name="widget2" value="0" required/>
<br>
<p>93XX-A</p>
<input type="text" name="widget3" value="0" required/>
<br>
<input type="radio" name="State" value="MO" checked>Missouri</input>
<br>
<input type="radio" name="State" value="IL">Illinois</input>
<br>
<input type="submit" value="submit"/>
</form>
</body>
</html>
You can do it like this
$('#submitIT').submit(function(e){
console.log("callingIT");
var wid1 = document.getElementById("widget1").value;
var wid2 = document.getElementById("widget2").value;
var wid3 = document.getElementById("widget3").value;
if(isNaN(wid1)||isNaN(wid2)||isNaN(wid3)){
console.log("all values entered must be numbers");
e.preventDefault();
}
else if(wid1 < 0 || wid2 < 0 || wid3 < 0){
console.log("all values must be greater than zero");
e.preventDefault();
}
if(wid1+wid2+wid3 > 25){
if(!confirm("you have more than 25 items. Will you accept the additional shipping?")){
e.preventDefault();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="submitIT" name="order" action="calculations.php" method="get">
<p>37AX-L:</p>
<input type="text" id="widget1" value="0" required/>
<br>
<p>42XR-J</p>
<input type="text" id="widget2" value="0" required/>
<br>
<p>93XX-A</p>
<input type="text" id="widget3" value="0" required/>
<br>
<input type="radio" id="State" value="MO" checked>Missouri</input>
<br>
<input type="radio" id="State" value="IL">Illinois</input>
<br>
<input type="submit" value="submit"/>
</form>
</body>
</html>