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>
Related
I am trying to build a Simple Profit and Loss page for my sales. The goal is:
One row equals One client.
Add a dynamic row based on number of clients.
For each row I need to input the sale amount and cost amount, then calculate the profit for that row(client).
Calculate the sum of all rows profit.
The issue: When I add a row, the button calculates only the first DOM row and not the result of the cloned ones as well.
$(document).ready(function() {
$("#addForm").click(function() {
$("#pnl").clone().appendTo(".originalPnlDiv");
});
});
function calculate() {
var salesPnl = document.getElementsbyClassName('sale').value;
var costPnl = document.getElementsbyClassName('cost').value;
var sum = document.getElementById('total').value = salesPnl - costPnl;
}
function totalProfit() {
var totalSalesPnl = document.getElementsbyClassName('sale').value;
var totalCostPnl = document.getElementsbyClassName('cost').value;
var totalSum = document.getElementById('grandTotal').value = totalSalesPnl - totalCostPnl;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>PNL</h1>
<div class="originalPnlDiv">
<form action="" id="pnl">
<select>
<option value="customerZ">customerZ</option>
<option value="customerX">customerX</option>
</select>
<input class="sale" type="number" placeholder="sale S$">
<input class="cost" type="number" placeholder="cost S$">
<input placeholder="invoice#">
<input type="date">
<input id="total"/>
</form>
</div>
<button id="addForm">Clone</button>
<button onclick="calculate()">calculate</button>
<br>
<br>
<button onclick="totalProfit()">Total Profit</button>
<p>The totalprofit is <span id="grandTotal"></span></p>
Thanks a lot for your help, I am only two months old regarding coding.
Have a nice day
don't use id when it's not going to be unique across the page.
re-organize your logic by moving the calculate button for each line
use document.querySelector and document.querySelectorAll
$(document).ready(function() {
$("#addForm").click(function() {
$("#pnl").clone().appendTo(".originalPnlDiv");
});
});
function calculate(button) {
var form = button.closest("form");
var salesPnl = form.querySelector('.sale').value;
var costPnl = form.querySelector('.cost').value;
var sum = salesPnl - costPnl;
form.querySelector('#total').value = sum;
return sum;
}
function totalProfit() {
var parent = document.querySelector(".originalPnlDiv");
var panels = parent.querySelectorAll("#pnl")
var grand = 0;
panels.forEach(function(panel) {
grand += calculate(panel);
})
document.querySelector("#grandTotal").innerText = grand;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>PNL</h1>
<div class="originalPnlDiv">
<form action="" id="pnl">
<select>
<option value="customerZ">customerZ</option>
<option value="customerX">customerX</option>
</select>
<input class="sale" type="number" placeholder="sale S$">
<input class="cost" type="number" placeholder="cost S$">
<input placeholder="invoice#">
<input type="date">
<input id="total" />
<button onclick="calculate(this); return false">calculate</button>
</form>
</div>
<button id="addForm">Clone</button>
<br>
<br>
<button onclick="totalProfit()">Total Profit</button>
<p>The totalprofit is <span id="grandTotal"></span></p>
I have been learning JavaScript and i am attempting to launch a new window on click after a user has placed info into a form fields and then placing that info into form fields in the newly launched window. I have read many posts and methods in Stackoverflow however i cant seem to get it to work properly.
Starting page HTML:
<form id="memCat" methed="get" class="member_catalogue">
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002_thumb.jpg" name="Red Bowl"></button>
<div class="cat_block">
<label class="cat_label" for="cat_name">Product Name:</label>
<input class="cat_input" type="text" id="catID" value="bepot002" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_description">Product Description:</label>
<input class="cat_input" type="text" id="catDesc" value="Ocre Red Pot" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_price">Per unit price:$</label>
<input class="cat_input" type="number" id="catVal" value="10" readonly>
</div>
</form>
New page HTML:
<form id="memOrder" method="post">
<div>
<label for="pname">Product Name:</label>
<input type="text" id="orderID" readonly>
</div>
<div>
<label for="pdescription">Product Description:</label>
<input type="text" id="orderDesc" readonly>
</div>
<div>
<label for="quantity">Quantity ordered:</label>
<input type="number" class="quantOrder" id="orderOrder" value="1" min="1" max="10">
</div>
<div>
<label for="ind_price">Per unit price: $</label>
<input type="number" class="quantCount" id="orderVal" readonly>
</div>
<div>
<label for="tot_price">Total Price: $</label>
<input type="number" class="quantCount" id="orderTotal" readonly>
</div>
<div>
<button type="reset">Clear Order</button>
<button type="submit" id="orderCalc">Calculate Total</button>
<button type="submit" id="orderPlace">Place Order</button>
</div>
</form>
Script i have to date:
function openMemberOrder() {
document.getElementById("orderID").value = document.getElementById("catID").document.getElementsByTagName("value");
document.getElementById("orderDesc").value = document.getElementById("catDesc").document.getElementsByTagName("value");
document.getElementById("orderVal").value = document.getElementById("catVal").document.getElementsByTagName("value");
memberOrderWindow = window.open('Member_Orders/members_order.html','_blank','width=1000,height=1000');
};
script and other meta tags in head are correct as other code is working correctly.
So after much trial and error i have had success with this:
On the submission page:
1. I created a button on the page that will capture the input form data
2. i created the localstorage function in JS
3. I then placed the script tag at the bottom of the page before the closing body tag
HTML
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002/bcpot002_thumb.jpg" name="Red Bowl"></button>
Javascript
var catID = document.getElementById("catID").value;
var catDesc = document.getElementById("catDesc").value;
var catVal = document.getElementById("catVal").value;
function openMemberOrder() {
var memberOrderWindow;
localStorage.setItem("catID", document.getElementById("catID").value);
localStorage.setItem("catDesc", document.getElementById("catDesc").value);
localStorage.setItem("catVal", document.getElementById("catVal").value);
memberOrderWindow = window.open('Member_Orders/members_order.html', '_blank', 'width=1240px,height=1050px,toolbar=no,scrollbars=no,resizable=no');
} ;
Script Tag
<script type="text/javascript" src="../../../JS/catOrder.js"></script>
I then created the new page with the following javascript in the header loading both an image grid as well as input element values:
var urlArray = [];
var urlStart = '<img src=\'../../../../Images/';
var urlMid = '_r';
var urlEnd = '.jpg\'>';
var ID = localStorage.getItem('catID');
for (var rowN=1; rowN<5; rowN++) {
for (var colN = 1; colN < 6; colN++){
urlArray.push(urlStart + ID + '/' + ID + urlMid + rowN + '_c' + colN + urlEnd)
}
}
window.onload = function urlLoad(){
document.getElementById('gridContainer').innerHTML = urlArray;
document.getElementById('orderID').setAttribute('value', localStorage.getItem('catID'));
document.getElementById('orderDesc').setAttribute('value', localStorage.getItem('catDesc'));
document.getElementById('orderVal').setAttribute('value', localStorage.getItem('catVal'));
};
I then created 2 buttons to calculate a total based on inputs and clearing values separately, the script for this was placed at the bottom of the page.
function total() {
var Quantity = document.getElementById('orderQuant').value;
var Value = document.getElementById('orderVal').value;
var Total = Quantity * Value;
document.getElementById('orderTotal').value = Total;
}
function clearForm() {
var i = 0;
var j = 0;
document.getElementById('orderQuant').value = i;
document.getElementById('orderTotal').value = j;
}
I am new to javascript and I have been working on this for 4 days now and I haven't made any progress. I have tried a bunch of different options. I saw an example like mine that worked...but it isn't working for me. :( I am trying to have the price adjust as the quantity of tickets changes. Below is the javascript and below that is the html. Any assistance is much appreciated! Thank you!
document.getElementById("totalTicketCost").value = 0 + "." + 00;
function ticketCost()
{
var ticketCost = 5.5;
var inputTicketQuantity = document.getElementById("inputTicketQuantity").value;
var totalTicketCost = parseFloat(ticketCost) * inputTicketQuantity;
if (!isNaN(totalTicketCost))
document.getElementById("totalTicketCost").innerHTML = totalTicketCost;
}
<form onsubmit="" ="return alertDetails()" id="formPurchaseTickets" enctype="text/plain" method="post" action="mailto:cmst388#xyz.com">
<h1>Ticket Purchasing Form</h1>
<p class="alert">Act fast! This transaction must be completed in <span id="timer"></span> minutes.</p>
<div class="field">
<label class="required">How many tickets would you like to purchase?</label>
<input id="inputTicketQuantity" tabindex="1" required type="number" value="0" name="ticket-quantity" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
$<span id="totalTicketCost">0.00</span>
</div>
<div id="contactInfo" style="display:none;">
<div class="field">
<label class="required">Name:</label>
<input required name="name" tabindex="2" type="text" placeholder="Enter name" pattern="[a-zA-Z\s]+" title="Enter only letters. e.g. Smith">
</div>
<div class="field">
<label class="required">E-mail:</label>
<input id="inputEmail" tabindex="3" required name="email" type="email" placeholder="Enter e-mail address" onblur="validateEmail()">
</div>
</div>
<hr>
<input type="submit" tabindex="4" value="Purchase Tickets"> <input type="reset">
</form>
<script src="event_registration.js"></script>
</body>
Going with only ES5 here (assuming you're not transpiling at this stage), I did a quick refactor.
var ticketInput = document.getElementById("totalTicketCost");
var inputTicketQuantity = document.getElementById("inputTicketQuantity");
var ticketCost = 5.5;
// Handle the precision up to >= $100
function changeCost( num ) {
var cost = new Number( parseFloat( num ) * ticketCost );
var precision = cost.toString().length === 3 ? 3 : 4;
return cost.toPrecision( precision );
}
inputTicketQuantity.addEventListener('input', function( event ) {
var value = event.target.value;
if ( !isNaN( value ) ) {
ticketInput.innerHTML = changeCost( value );
}
});
You definitely want to separate out the JS from the HTML as much as possible, avoid the hard to read inline stuff like <form onsubmit="" ="return alertDetails()", should at least be <form onsubmit="return alertDetails()" to fix it.
Add an event listener to you quantity field, and recalculate price.
document.querySelector("#inputTicketQuantity").addEventListener("input", function() {
let count = this.value;
calculatePrice(count);
});
Your question is not very specific on what you're trying to achieve, but here is functionality to update your total cost as the user adds tickets -
In JS:
function updateCost(count)
{
var ticketCost = 5.5;
document.getElementById("totalTicketCost").innerHTML = count * ticketCost;
}
In HTML
<input id="inputTicketQuantity" tabindex="1" required type="number" value="0" name="ticket-quantity" onchange="updateCost(this.value)" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
You have to call function ticketCost() on value change event of input quantity textbox
<input id="inputTicketQuantity" onkeydown="ticketCost()" tabindex="1" required type="number" value="0" name="ticket-quantity" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
Or you can add listener in JavaScript as
document.getElementById("inputTicketQuantity").addEventListener("onkeydown", ticketCost);
Add it outside your JavaScript function ticketCost()
How do I display something like a recommendation list after a user calculate a result from the inputs? E.g having the user to key in the salaries of the family and calculating the PCI (Per capita income) and after they key in and press on the calculate button which then will trigger a list of recommendations based on the amount of PCI the family have (Maybe tables that shows different results based on different categories of PCI?)
<!DOCTYPE html>
<html>
<head>
<script src="common.js"></script>
<script>
function cal()
{
var salary1 = document.getElementById('salary1').value;
var salary2 = document.getElementById('salary2').value;
var salary3 = document.getElementById('salary3').value;
var salary4 = document.getElementById('salary4').value;
var members = document.getElementById('members').value;
var total = (parseInt(salary1) + parseInt(salary2) + parseInt(salary3) + parseInt(salary4)) / parseInt(members);
document.getElementById('total').value = total;
alert (total);
}
</script>
</head>
<body>
<h1>Want to know which bursary your eligible?</h1>
<input id="salary1" value="" placeholder="Enter your 1st family income..."/>
<input id="salary2" value="" placeholder="Enter your 2nd family income..."/>
<input id="salary3" value="" placeholder="Enter your 3rd family income..."/>
<input id="salary4" value="" placeholder="Enter your 4th family income..."/>
<input id="members" value="" placeholder="Enter the total number of family members..."/>
<br>
<button onclick="cal()"> Calculate PCI!</button>
<br>
Total: <input id="total"> </input>
</body>
</html>
You can create a hidden div that holds the data then show that div when user clicks the button
HTML:
<div id="divToShow" style="display:none;" class="table_list" >
//put your data table here
</div>
<input type="button" name="myButton" value="Show Div" onclick="showDiv()" />
Javascript:
function showDiv() {
document.getElementById('divToShow').style.display = "block";
}
This should get you there: Jsfiddle.
<form id="form">
<input id="number1" type="number" min="1" name="number" placholder="add value one"> +
<input id="number2" type="number" min="1" name="number" placholder="add value one">
<button>Submit</button>
</form>
var form = document.getElementById('form');
number1 = document.getElementById('number1');
number2 = document.getElementById('number2');
form.onsubmit = function() {
var total = +number1.value + +number2.value; // add + before
alert( total );
};
function cal(){
var salary1 = document.getElementById('salary1').value;
var salary2 = document.getElementById('salary2').value;
var salary3 = document.getElementById('salary3').value;
var salary4 = document.getElementById('salary4').value;
var members = document.getElementById('members').value;
var recommanted;
var recommandations=[
{maxpci:1000,recommandation:'first_recommandation'},
{maxpci:2000,recommandation:'second_recommandation'},
{maxpci:3000,recommandation:'third_recommandation'},
{maxpci:6000,recommandation:'fourth_recommandation'}
];
var total=(parseInt(salary1) + parseInt(salary2) + parseInt(salary3) + parseInt(salary4)) / parseInt(members);
if(recommandations[recommandations.length - 1].maxpci < total ){recommanted=recommandations[recommandations.length - 1].recommandation;}
else{
for (var i = 0; i < recommandations.length; i++) {
if(total <= recommandations[i].maxpci){
recommanted=recommandations[i].recommandation;break;}
}}
document.getElementById('result').innerHTML = "Your PCI : "+total+"</br>Recommandation : "+recommanted;
}
<h1>Want to know which bursary your eligible?</h1>
<input id="salary1" type="number" value="" placeholder="Enter your 1st family income..."/>
<input id="salary2" type="number" value="" placeholder="Enter your 2nd family income..."/>
<input id="salary3" type="number" value="" placeholder="Enter your 3rd family income..."/>
<input id="salary4" type="number" value="" placeholder="Enter your 4th family income..."/>
<input id="members" type="number" value="" placeholder="Enter the total number of family members..."/>
</br>
<button onclick="cal()"> Calculate PCI!</button>
</br>
<div id="result">
</div>
I currently have been working on this code and I can't seem to figure it out. I am planning to make it so that if the radio button is pressed that shipping is not free, that an input field pops up to specifying what the addition cost will be using DOM. I am also trying to figure out how to add text to describe the input field, and to validate the input field.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function myFunction() {
var x = document.createElement("INPUT");
var c = 1;
if (c = 1) {
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
// var br = document.createElement("br");
// sp2.appendChild(br);
// alert("added break");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
c++;
alert("Added Text Box");
}
}
</script>
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id = "tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked /> Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;"/> No
<p class="boldParagraph" id = "emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br><br>
<button>Submit</button>
</form>
</body>
</html>
Create a label element and populate text using innerHTML. and then append to DOM.
Example Snippet:
function myFunction() {
var label = document.createElement("label");
label.innerHTML = "<br>Shipment Cost : ";
var x = document.createElement("INPUT");
var c = 1;
if (c = 1) {
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
// var br = document.createElement("br");
// sp2.appendChild(br);
// alert("added break");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
parentDiv.insertBefore(label, x);
c++;
alert("Added Text Box");
}
}
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked />Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;" />No
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br>
<br>
<button>Submit</button>
</form>
OR
You can keep the text box hidden and show it when user clicks no. Also, apply validations only when no is selected for shipment radio button.
I suggest use jQuery, see the snippet below:
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
var radioButtons = $("[name=tip3]");
radioButtons.on("change", function() {
if ($("[name=tip3]:checked").val() == "3") {
$("#shipmentDetail").hide();
} else {
$("#shipmentDetail").show();
}
})
$("#submit").on("click", function() {
var flag = true;
if ($("[name=tip3]:checked").val() == "4") {
if ($("#shipmentDetail").val() == "") {
flag = false;
alert("enter some value");
}
}
//other validations here
if (flag) {
$("#form").submit()
}
})
#shipmentDetail {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" action="#" method="post">
<p class="boldParagraph">Upload an Image:</p>
<input type="file" id="pic" accept="image/*" required>
<p class="boldParagraph">Name of seller:</p>
<input class="averageTextBox" type="text" id="seller" value="" required>
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" checked />Yes
<input type="radio" name="tip3" value="4" />No
<label id="shipmentDetail" for="price">Shipment Cost:
<input id="price" type="text" value="" />
</label>
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<p class="boldParagraph">Closing date for auction:</p>
<input type="date" id="closeDate" value="" required>
<br>
<br>
<button id="submit">Submit</button>
</form>
replace
alert("Added Text Box");
with:
var additional_fees = prompt("Type in");
x.setAttribute("value", additional_fees)