Pricing values and storing them to access on checkout page - javascript

I am currently having troubles in finding a way where I can price my two radio buttons and when clicked on one of them, the price goes to the checkout page which a user can later access once completed the booking page.
So in steps:
User clicks on standard or first class ticket.
User clicks on the input value of “number” and chooses how many adults and child tickets they need (the number of adults and children are multiplied by the ticket price).
The total price is given below as a input type “text”.
User then clicks on the checkout button which will direct them to the checkout page.
User will be able to see individually the number of tickets bought for adults and child also their prices and total.
Now I have managed to give the standard and First class a price by using variables, now this next step I am confused at.
function standardfunction() {
var Type1 = document.getElementById('Standard').value;
var adult = document.getElementById('adult').value;
var child = document.getElementById('child').value;
var Total_Cost
var Type1 = 6
var adult = 1
var child = 0.5
alert(Total_Cost = adult * Type1);
}
function firstclassfunction() {
var Type2 = document.getElementById('First-Class').value;
var adult = document.getElementById('adult').value;
var child = document.getElementById('child').value;
var Total_Cost
var Type2 = 10
var adult = 1
var child = 0.5
alert(Total_Cost = adult * Type2);
}
<label for="Adult-ticket" class="center-label">Adults(+16)</label>
<input type="number" id="adult" name="user_adult">
<label for="child-ticket" class="center-label">Child</label>
<input type="number" id="child" name="user_child">
<input type="radio" id="Standard" name="Type" value="Standard" onclick="standardfunction()">
<label class="light" for="Standard">Standard</label><br>
<input type="radio" id="First-Class" name="Type" value="First-Class" onclick="first-classfunction()>
<label class="light" for="First-Class">First Class</label><br><br>
<input type = "button" value="checkout" id="checkoutbtn">
Another problem is that how can I price the radio button so that the radio button is the default adult price but when they also had child tickets it gives them as not one full adult ticket but half so:
Adult = £6
Child = £3

It's important to note that input values are recorded as strings and need to be converted to numbers first.
Use Number or parseInt first to convert to an integer.
You are also declaring the same variables twice, and the second time they override the first. You want to get input from the user, so I deleted the second instances of your variable.
Also
alert(Total_Cost = adult * Type2);
isn't proper syntax. It should be
alert(adult * Type2);
It's also possible to combine the two functions into one
Your HTML code now needs to be modified. You need to run the function when the submit button has been pressed.
function calculateFare() {
var option = document.querySelector('input[type=radio]:checked')
var fare = option.getAttribute("value");
var ad = Number(document.getElementById('adult').value);
var ch = Number(document.getElementById('child').value);
var cost = (fare == "Standard") ? (ad * 6) + (ch * 3) : (ad * 10) + (ch * 5);
document.getElementById("total-cost").innerHTML = cost;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="Adult-ticket" class="center-label">Adults(+16)</label>
<input type="number" id="adult" name="user_adult">
<label for="child-ticket" class="center-label">Child</label>
<input type="number" id="child" name="user_child">
<input type="radio" id="Standard" name="Type" value="Standard">
<label class="light" for="Standard">Standard</label><br>
<input type="radio" id="First-Class" name="Type" value="First-Class">
<label class="light" for="First-Class">First Class</label><br><br>
<input type = "button" value="checkout" id="checkoutbtn" onclick="calculateFare()">
<p id="total-cost"></p>

Related

How do include javascript to item checkbox so that the selected box calculates the price value automatucally?

Display four or more items to purchase along with their corresponding purchase price (use check boxes to allow selection of the items you wish to purchase). Give the checkboxes the name item_0, item_1, etc.
Include a Total field which automatically totals your purchases as each item is checked/unchecked or the specified quantity changes. Give this field the name total.
I need some help with this.
Here is the code of the simplest I have been able to do so far.
<h3> Cart </h3>
<input type = "checkbox" id = "item_0" name ="item_0" value = "Malt">
<label> Beta Malt </label>
<input type = "checkbox" id = "item_1" name ="item_1" value = "bread">
<label> A1 Bread </label>
<input type = "checkbox" id = "item_0" name ="item_2" value = "noodles">
<label> Indomie </label>
<input type = "checkbox" id = "item_0" name ="item_3" value = "milk">
<label> Cowbell </label>
First, change attributes name for the same.
You can use for example, How to check multiple checkboxes with JavaScript?.
Using this idea.
var checkboxes = document.querySelectorAll('input[name="' + nameCheckbox + '"]:checked'), values = 0;
Array.prototype.forEach.call(checkboxes, function(el) {
values += parseInt(el.value);
});
alert(values);

value from a JavaScript form

I'm building a form that allows to calculate the Bishop Score: https://jsfiddle.net/molecoder/1oqxsw81/ .
The user is allowed to select between 4 options and each of these options (0 cm, 1-2 cm, ...) have an associated value.
Here is the HTML code for the form:
<form action="" id="bishopform" onsubmit="return true;">
<div>
<fieldset>
<legend>Bishop score</legend>
<p>(modify one field to see the score)</p>
<div id="bishopScore"></div>
<label><b>Cervical Dilatation</b></label><br/>
<label class='radiolabel'><input type="radio" name="selectedcervicaldilatation" value="cerdi1" onclick="calculateTotalBishop()"/>0 cm</label><br/>
<label class='radiolabel'><input type="radio" name="selectedcervicaldilatation" value="cerdi2" onclick="calculateTotalBishop()" checked/>1-2 cm</label><br/>
<label class='radiolabel'><input type="radio" name="selectedcervicaldilatation" value="cerdi3" onclick="calculateTotalBishop()" />3-4 cm</label><br/>
<label class='radiolabel'><input type="radio" name="selectedcervicaldilatation" value="cerdi4" onclick="calculateTotalBishop()"/>5-6 cm</label><br/>
<br/>
</fieldset>
</div>
</form>
Here is the JavaScript code to process the selection:
var cervical_dilatation = new Array();
cervical_dilatation["cerdi1"]=0;
cervical_dilatation["cerdi2"]=1;
cervical_dilatation["cerdi3"]=2;
cervical_dilatation["cerdi4"]=3;
// getCervicalDilation() finds the points based on the answer to "Cervical Dilation".
// Here, we need to take user's the selection from radio button selection
function getCervicalDilation()
{
var cerdiPoints=0;
//Get a reference to the form id="bishopform"
var theForm = document.forms["bishopform"];
//Get a reference to the answer the user Chooses name=selectedcervicaldilatation":
var selectedCervicalDilation = theForm.elements["selectedcervicaldilatation"];
//Here since there are 4 radio buttons selectedCervicalDilation.length = 4
//We loop through each radio buttons
for(var i = 0; i < selectedCervicalDilation.length; i++)
{
//if the radio button is checked
if(selectedCervicalDilation[i].checked)
{
//we set cerdiPoints to the value of the selected radio button
cerdiPoints = cervical_dilatation[selectedCervicalDilation[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cerdiPoints
return cerdiPoints;
}
function calculateTotalBishop()
{
//Here we get the Bishop Score by calling our function
//Each function returns a number so by calling them we add the values they return together
var bishopScore = 3*getCervicalDilation() + 1;
//display the result
var divobj = document.getElementById('bishopScore');
divobj.style.display='block';
divobj.innerHTML = bishopScore+"% likelihood that induction will be successful";
}
For any particular reason, I'm not able to see the result of user's selection.
How can this be fixed?
The problem is that calculateTotalBishop() has to be a global function... But jsfiddle wraps your code in window.onload... And that's the reason an error is logged which says Uncaught ReferenceError: calculateTotalBishop is not defined
To fix this just change the "Load Type" in js settings in jsfiddle from "onLoad" to "No wrap - in body"... That will solve the problem
Working fiddle : https://jsfiddle.net/1oqxsw81/1/
PS:
It's recommended to use addEventListener in js instead of onclick in html
and it'll be much better if you use onchange event because the value can be changed from a keyboard also
It doesn't work because of the how the JSFiddle handles their scripts in the preview. Because they inject the entered script into iframe by using window.onload method, your functions become private in the new scope, and can't be called from html.
Your code works expected as it is in the fiddle from SO:
var cervical_dilatation = new Array();
cervical_dilatation["cerdi1"]=0;
cervical_dilatation["cerdi2"]=1;
cervical_dilatation["cerdi3"]=2;
cervical_dilatation["cerdi4"]=3;
// getCervicalDilation() finds the points based on the answer to "Cervical Dilation".
// Here, we need to take user's the selection from radio button selection
function getCervicalDilation()
{
var cerdiPoints=0;
//Get a reference to the form id="bishopform"
var theForm = document.forms["bishopform"];
//Get a reference to the answer the user Chooses name=selectedcervicaldilatation":
var selectedCervicalDilation = theForm.elements["selectedcervicaldilatation"];
//Here since there are 4 radio buttons selectedCervicalDilation.length = 4
//We loop through each radio buttons
for(var i = 0; i < selectedCervicalDilation.length; i++)
{
//if the radio button is checked
if(selectedCervicalDilation[i].checked)
{
//we set cerdiPoints to the value of the selected radio button
cerdiPoints = cervical_dilatation[selectedCervicalDilation[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cerdiPoints
return cerdiPoints;
}
function calculateTotalBishop()
{
//Here we get the Bishop Score by calling our function
//Each function returns a number so by calling them we add the values they return together
var bishopScore = 3*getCervicalDilation() + 1;
//display the result
var divobj = document.getElementById('bishopScore');
divobj.style.display='block';
divobj.innerHTML = bishopScore+"% likelihood that induction will be successful";
}
#bishopScore{
padding:10px;
font-weight:bold;
background-color:limegreen;
}
<form action="" id="bishopform" onsubmit="return true;">
<div>
<fieldset>
<legend>Bishop score</legend>
<p>(modify one field to see the score)</p>
<div id="bishopScore"></div>
<label><b>Cervical Dilatation</b></label><br/>
<label class='radiolabel'><input type="radio" name="selectedcervicaldilatation" value="cerdi1" onclick="calculateTotalBishop()"/>0 cm</label><br/>
<label class='radiolabel'><input type="radio" name="selectedcervicaldilatation" value="cerdi2" onclick="calculateTotalBishop()" checked/>1-2 cm</label><br/>
<label class='radiolabel'><input type="radio" name="selectedcervicaldilatation" value="cerdi3" onclick="calculateTotalBishop()" />3-4 cm</label><br/>
<label class='radiolabel'><input type="radio" name="selectedcervicaldilatation" value="cerdi4" onclick="calculateTotalBishop()"/>5-6 cm</label><br/>
<br/>
</fieldset>
</div>
</form>

Why is the multiplication happening only after refresh?

I have a calculator. This has a form which, for certain calculations, works only when I refresh the page. Addition works but multiplication only works after refresh. Why is that?
I don't want to use JQuery!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Card Form</title>
<link href="styles/cardform.css" rel="stylesheet" type="text/css" />
</head>
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="cardform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Check Quotes</legend>
<label>Size Of the Card</label>
<label>Width in cm: </label> <input type="text" id="width" />
<label>Height in cm: </label> <input type="text" id="height" />
<br/>
<br/>
<label class='radiolabel'><input type="radio" name="selectedcard1" value="Round13" onclick=""/>Standard</label>
<label class='radiolabel'><input type="radio" name="selectedcard1" value="Round14" onclick="" />Toughened</label><br/>
<br/>
<label>Card: </label>
<label class='radiolabel'><input type="radio" name="selectedcard2" value="Round17" onclick=""/>Clear</label>
<label class='radiolabel'><input type="radio" name="selectedcard2" value="Round18" onclick="" />Frosted</label>
<label class='radiolabel'><input type="radio" name="selectedcard2" value="Round19" onclick="" />Leaded</label>
<label class='radiolabel'><input type="radio" name="selectedcard2" value="Round20" onclick="" />White Bar</label>
<br/>
<label>Frame: </label>
<label class='radiolabel'><input type="radio" name="selectedcard3" value="Round21" onclick=""/>uPVC</label>
<label class='radiolabel'><input type="radio" name="selectedcard3" value="Round22" onclick="" />Metal</label>
<label class='radiolabel'><input type="radio" name="selectedcard3" value="Round23" onclick=""/>Wood</label>
<br/>
<input type="submit" value="Calculate" onClick="calculateTotal()" />
<INPUT TYPE="reset" VALUE="RESET" onClick="resetIt()" />
<div id="totalPrice"></div>
</fieldset>
</div>
</div>
</form>
</div>
<!--End of wrap-->
</body>
<script>
var size1 = document.getElementById("width").value;
var size2 = document.getElementById("height").value;
var total_size = ((size1 * size2) / 10000);
var card_prices = new Array();
card_prices["Round13"] = (total_size * 67);
card_prices["Round14"] = (total_size * 87);
card_prices["Round17"] = (total_size * 0.05);
card_prices["Round18"] = (total_size * 0.65);
card_prices["Round19"] = (total_size * 0.85);
card_prices["Round20"] = (total_size * 0.95);
function getCardSizePrice2() {
var cardSizePrice = 0;
//Get a reference to the form id="cardform"
var theForm = document.forms["cardform"];
//Get a reference to the card the user Chooses name=selectedCard":
var selectedCard1 = theForm.elements["selectedcard1"];
//Here since there are 4 radio buttons selectedCard.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCard1.length; i++) {
//if the radio button is checked
if (selectedCard1[i].checked) {
//we set cardSizePrice to the value of the selected radio button
//i.e. if the user choose the 8" card we set it to 25
//by using the card_prices array
//We get the selected Items value
//For example card_prices["Round8".value]"
cardSizePrice = card_prices[selectedCard1[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cardSizePrice
return cardSizePrice;
}
function getCardSizePrice3() {
var cardSizePrice = 0;
//Get a reference to the form id="cardform"
var theForm = document.forms["cardform"];
//Get a reference to the card the user Chooses name=selectedCard":
var selectedCard = theForm.elements["selectedcard2"];
//Here since there are 4 radio buttons selectedCard.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCard.length; i++) {
//if the radio button is checked
if (selectedCard[i].checked) {
cardSizePrice = card_prices[selectedCard[i].value];
break;
}
}
return cardSizePrice;
}
function getCardSizePrice4() {
card_prices["Round21"] = 2;
card_prices["Round22"] = 5;
card_prices["Round23"] = 5;
var cardSizePrice = 0;
//Get a reference to the form id="cardform"
var theForm = document.forms["cardform"];
//Get a reference to the card the user Chooses name=selectedCard":
var selectedCard = theForm.elements["selectedcard3"];
//Here since there are 4 radio buttons selectedCard.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCard.length; i++) {
//if the radio button is checked
if (selectedCard[i].checked) {
cardSizePrice = card_prices[selectedCard[i].value];
break;
}
}
return cardSizePrice;
}
var divobj = document.getElementById('totalPrice');
function calculateTotal() {
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var cardPrice = getCardSizePrice2() + getCardSizePrice3() + getCardSizePrice4();
//display the result
divobj.style.display = 'block';
divobj.innerHTML = "Total Price For the Card: £" + " " + cardPrice;
displaytotal(divobj);
}
function displaytotal() {
}
function hideTotal() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
function resetIt() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
</script>
</html>
I understand you've found your issue (I believe it had to do with the fact that you had your code set up with a submit button and you had totals being calculated as soon as the page load event triggered, rather than upon a click of the total button).
But, beyond that, you may still want to look at this answer very carefully as the code you have is just awful in many regards:
HTML:
Your HTML was not being used correctly. You were not using <label>
or <fieldset> elements properly.
Since you were really just needing a calculator that doesn't actually
submit the data anywhere, you shouldn't have a submit button.
You were using inline HTML event handlers (onsubmit, onclick,
etc.), which should not be used because:
They create "spaghetti code" that is difficult to read and leads to
duplication of code.
They cause global event handling wrapper functions to be implicitly
created around the attribute values that you supply that make the
binding of the this object not work as expected.
They don't follow W3C Standards for Event Handling
JavaScript:
You were setting up variables for the HTML elements you were going to
use inside your various functions, which meant that every time the
function runs, it has to re-scan the document all over again to find
the element.
You were using an array when an Object was more appropriate.
You had essentially the same function written 3 times instead of just
having it once and passing an argument to it that can change as you
need it to.
Here is a cleaned up version that follows best-practices, semantics and doesn't repeat itself. See the inline comments for specifics.
window.addEventListener("DOMContentLoaded", function(){
// Get references to DOM elements that we'll need access to just once. Don't set variables
// up to store their values at first. Set the variable to the elmement. That way, you can
// go back to the element as often as you need to in order to get any property value you
// like, without having to re-scan the document for it all over again:
var size1 = document.getElementById("width");
var size2 = document.getElementById("height");
var divObj = document.getElementById('totalPrice');
var theForm = document.getElementById("cardform");
var selectedCard1 = theForm.querySelectorAll("[name=selectedcard1]");
var selectedCard2 = theForm.querySelectorAll("[name=selectedcard2]");
var selectedCard3 = theForm.querySelectorAll("[name=selectedcard3]");
var calc = document.querySelector("input[type=button]");
var res = document.querySelector("input[type=reset]");
// Set up event handlers for various DOM elements:
calc.addEventListener("click", calculateTotal);
res.addEventListener("click", reset);
// Create a storage mechanism that holds "keys" and associated "values"
// Arrays can only do this with sequential numeric indexes. Objects, do it
// with string property names.
var card_prices = {};
// No reason to have 3 functions that all do basically the same thing but only
// to different objects. Just have one function that accepts a reference to the
// radiobuttons it needs to work with
function getCardSizePrice(cards){
var cardSizePrice = 0;
// Loop through each radio button in the passed in group
for(var i = 0; i < cards.length; i++) {
//if the radio button is checked
if(cards[i].checked) {
// Lookup the value of the selected radio button in our object and get the
// associate property value
cardSizePrice = card_prices[cards[i].value];
// No reason to continue if we get a match
break;
}
}
// We return the cardSizePrice
return cardSizePrice;
}
function calculateTotal() {
// You didn't have the following code in this funciton, so it was running immediately
// when the page loaded.
// Remember, values that you take out of form elements are strings!
// If you want to treat them as numbers, you should explicitly convert them
// to numbers first:
var s1 = parseFloat(size1.value);
var s2 = parseFloat(size2.value);
var total_size = (s1 * s2) / 10000;
// Set all the property values
card_prices["Round13"] = total_size * 67,
card_prices["Round14"] = total_size * 87,
card_prices["Round17"] = total_size * .05,
card_prices["Round18"] = total_size * .65,
card_prices["Round19"] = total_size * .85,
card_prices["Round20"] = total_size * .95,
card_prices["Round21"] = 2;
card_prices["Round22"] = 5;
card_prices["Round23"] = 5;
// Here we get the total price by calling our function
// Each function returns a number so by calling them we add the values they return together
var cardPrice = getCardSizePrice(selectedCard1) +
getCardSizePrice(selectedCard2) +
getCardSizePrice(selectedCard3);
displayTotal(cardPrice);
}
function displayTotal(price) {
// display the result
divObj.classList.remove("hidden");
divObj.innerHTML = "Total Price For the Card: £" + " " + price.toFixed(2);
}
function reset(){
divObj.innerHTML = "";
}
});
#totalPrice { background-color:#ff0; } // Default style for element
#panel { margin-top: 1em;}
fieldset { margin-bottom:1em; }
<body>
<div id="wrap">
<form action="#" id="cardform">
<div class="cont_order">
<h1>Check Quotes</h1>
<!-- Fieldsets are for logical grouping of form elements. While they do have a
visual component to them, they are primarially for accessibility for
visually impaired. -->
<fieldset>
<legend>Size Of the Card</legend>
<!-- Labels associate with form elements via the "for" attribute and the target
element's "id" attribute. They aren't just for displaying random text.
They are a key aspect of designing for accessibility. You can click/touch the
label and activate the associated form element. -->
<label for="width">Width in cm:</label> <input type="text" id="width">
<label for="height">Height in cm:</label> <input type="text" id="height">
<br><br>
<input type="radio" name="selectedcard1" id="selectedcard1a" value="Round13">
<label for="selectedcard1a" class='radiolabel'>Standard</label>
<input type="radio" name="selectedcard1" id="selectedcard1b" value="Round14">
<label for="selectedcard1b" class='radiolabel'>Toughened</label><br>
</fieldset>
<fieldset>
<legend>Card</legend>
<input type="radio" name="selectedcard2" id="selectedcard2a" value="Round17">
<label for="selectedcard2a" class='radiolabel'>Clear</label>
<input type="radio" name="selectedcard2" id="selectedcard2b" value="Round18">
<label for="selectedcard2b" class='radiolabel'>Frosted</label>
<input type="radio" name="selectedcard2" id="selectedcard2c" value="Round19">
<label for="selectedcard2c" class='radiolabel'>Leaded</label>
<input type="radio" name="selectedcard2" id="selectedcard2d" value="Round20">
<label for="selectedcard2d" class='radiolabel'>White Bar</label>
</fieldset>
<fieldset>
<legend>Frame</legend>
<input type="radio" name="selectedcard3" id="selectedcard3a" value="Round21">
<label for="selectedcard3a" class='radiolabel'>uPVC</label>
<input type="radio" name="selectedcard3" id="selectedcard3b" value="Round22">
<label for="selectedcard3b" class='radiolabel'>Metal</label>
<input type="radio" name="selectedcard3" id="selectedcard3c" value="Round23">
<label for="selectedcard3c" class='radiolabel'>Wood</label>
</fieldset>
<div id="panel">
<input type="button" value="Calculate">
<input type="reset" value="Reset">
<div id="totalPrice"></div>
</div>
</div>
</form>
</div>

radio button .checked to perform a math expression using user input javascript

I have two textboxes where a user enters a number into each one and then clicks a radio button to select the mathematical operation to be performed upon the calculate button.This is for a homework assignment, so only javascript and html
are being used, no jquery. Currently when I click the button, nothing appears to happen and I am getting no console errors...
HTML
<div>
<p>Enter two numbers, select a math, then click the button.<br>
The answer will be shown below.</p>
<form>
1st number: <input type="text" name="number1">
2nd number: <input type="text" name="number2">
<br>
<input type="radio" name="add">Add <br>
<input type="radio" name="subtract">Subtract <br>
<input type="radio" name="multiply">Multiply <br>
<input type="radio" name="division">Division <br>
<input type="button" name="calc" onclick="calculate()" value="Calculate"> <br>
</form>
<p id="math_res"></p>
</div>
Javascript
function calculate(){
var num1 = parseInt("document.getElementsByName('number1').value;", 10);
var num2 = parseInt("document.getElementsByName('number2').value;", 10);
var add = document.getElementsByName("add");
var sub = document.getElementsByName("subtract");
var multi = document.getElementsByName("multiply");
var divis = document.getElementsByName("division");
var res = document.getElementById("math_res").innerHTML;
if (add.checked == true){
res = num1 + num2;
}
else if ( sub.checked == true){
res = num1 + num2;
}
else if (multi.checked == true){
res = num1 * num2;
}
else if (divis.checked == true){
res = num1 / num2;
}
}
I thought my function would take the input from the two text boxes and convert the user input to an integer and assign them to variable num1 and num2. Then assign each radio button to a variable to reduce typing of document.get...
that each if statement would check to see if that radio but was checked. If true perform calculation if false move to next if statement and display the results in a paragraph element.
where did I go wrong?
You have a couple of issues.
getElementsByName returns a collection of elements, not a single element so:
var add = document.getElementsByName("add");
will assign undefined to add. But you don't need to use it, just reference the controls as named properties of the form. Pass a reference to the button from the listener:
<input type="button" name="calc" onclick="calculate(this)" value="Calculate">
Then in the function get the form:
function calculate(element) {
var form = element.form;
Now just do:
var num1 = parseInt(form.number1.value, 10);
and so on, which also fixes the other issues you have with referencing the controls.
Also, radio buttons need to have the same name so that only one is selectable, so as Felix says, give them all the same name and differentiate on value (or class or some other attribute value). You'll need to loop over them to find out the operation to perform, so the HTML might be:
<input type="radio" name="operation" value="add">Add <br>
<input type="radio" name="operation" value="subtract">Subtract <br>
<input type="radio" name="operation" value="multiply">Multiply <br>
<input type="radio" name="operation" value="division">Division <br>
Then to get the operation:
var radios = form.operation;
var op;
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) {
op = radios[i].value;
break;
}
}
Now check the value of op to work out whether to add, subtract, etc.
Here's a quick example, I don't recommend inline scripts like this but it's handy for playing.
<form>
<input type="radio" name="operation" value="add">Add <br>
<input type="radio" name="operation" value="subtract">Subtract <br>
<input type="radio" name="operation" value="multiply">Multiply <br>
<input type="radio" name="operation" value="division">Division <br>
<input type="button" onclick="
var form = this.form;
var radios = form.operation;
var op;
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) {
op = radios[i].value;
break;
}
}
form.selectedOperation.value = op || 'No operation selected';
" value="Get selected operation">
<input type="text" readonly name="selectedOperation"><br>
<input type="reset">
</form>
There are a few issues I can notice.
1.
getElementsByName returns a NodeList, which is Array-like. You need to retrieve the first element in the NodeList before accessing its value. For example,
document.getElementsByName('number1')[0].value
2.
You are passing a literal code string to parseInt. You should write something like
parseInt(document.getElementsByName('number1')[0].value, 10);
3.
The code var res = document.getElementById('math_res').innerHTML stores a reference to the innerHTML of the element. When you assign res = num1 + num2 for example, you are simply overwriting the reference, instead of actually altering the innerHTML. To correct this,
var elem = document.getElementById('math_res');
// later...
elem.innerHTML = num1 + num2;
4. You are incorrectly defining multiple radio buttons with different names. In order for the browser to render them as a "radio button group" where only one can be selected, they must have the same name, but different "value" attributes. See RobG's answer or the Plunkr below for an example of how to define the radio button group and extract its value using JavaScript.
A working version of your code is here.
Edit Please note that these are minimal edits to make your code work. RobG's answer shows a more correct way of extracting the values of form fields.
Here is my version, hope it helps you.
<!DOCTYPE html>
<html>
<body>
<div>
<p>Enter two numbers, select a math, then click the button.<br>
The answer will be shown below.</p>
<form>
1st number: <input type="text" name="number1" id = 'number1'>
2nd number: <input type="text" name="number2" id = 'number2'>
<br>
<input type="radio" name="button" id = 'add' >Add <br>
<input type="radio" name="button" id = 'substract'>Subtract <br>
<input type="radio" name="button" id = 'multiply'>Multiply <br>
<input type="radio" name="button" id = 'division'>Division <br>
<input type="button" name="calc" onclick="calculate()" value="Calculate"> <br>
</form>
<p id="math_res"></p>
</div>
<script>
function calculate(){
//Obtaining the references to the text inputs
var number1 = parseInt(document.getElementById('number1').value);
var number2 = parseInt(document.getElementById('number2').value);
//Reference of the result Box
var resultBox = document.getElementById('math_res');
resultBox.innerHTML = '';
//Reference of the radio buttons
var buttonAdd = document.getElementById('add');
var buttonSubstract = document.getElementById('substract');
var buttonMultiply = document.getElementById('multiply');
var buttonDivision = document.getElementById('division');
//Make the magic
if(buttonAdd.checked == true){
resultBox.innerHTML = number1 + number2
}
else{
if(buttonSubstract.checked == true){
resultBox.innerHTML = number1 - number2
}
else{
if(buttonMultiply.checked == true){
resultBox.innerHTML = number1 * number2
}
else{
if(buttonDivision.checked == true){
resultBox.innerHTML = number1 / number2
}
}
}
}
}
</script>
</body>

Validating field input based on a percentage of field value

I've created a form in Acrobat XI pro. I have 3 radio buttons, which when selected, populate a single number value into a field...here is the code I'm using for this:
var v = this.getField("marketRadioButtons").value;
event.value = (v=="Off") ? "" : v;
This works fine, but now I'm trying to restrict the user edit of this this field to a maximum 40% of the default value per selection of each radio button.
I've been able to accomplish this by simply creating 3 fields - one for each radio button, and using validation against an actual number (ie., selecting radio button1 populates text field1 with $700, so:
event.rc = event.value < 980 if (!event.rc) app.alert ("..."))
but prefer to use only one text field for each radio button value.
Any help is greatly appreciated!
Try this solution! I added some new happiness that does as you wish!
The way this program works:
You click a checkbox.
You type a new value for that number.
You click update.
It updates the number by the checkboxes.
Checks:
If the number entered is more than 1.4 * current value, an alert will fire and the value will not be updated.
If no number is entered, nothing happens.
Html:
<form id="form1" action="">
<input class='1' type="radio" onclick="display(this)" name="box" value="700"><span class="1">700</span><br>
<input class='2' type="radio" onclick="display(this)" name="box" value="1200"><span class="2">1200</span><br>
<input class='3' type="radio" onclick="display(this)" name="box" value="1500"><span class="3">1500</span>
</form><br>
<form action="">
<input type="text" id="output" value="$"/>
<button type="button" onclick="update(this)">Update</button>
</form>
Javascript:
var checkedValue = {
'class':0,
'value':0,
}
display = function(me) {
var textbox = document.getElementById('output');
textbox.value = "$" + me.value;
checkedValue.value = Number(me.value);
checkedValue.class = me.className;
}
update = function(me) {
var price = me.form.output.value;
// if no value entered, newAmount sets to 0
var newAmount = Number(price.substring(1, price.length));
if (newAmount) {
var maxChange = Math.round(1.4 * checkedValue.value);
if (newAmount <= maxChange) {
document.getElementsByClassName(checkedValue.class)[1].innerHTML = newAmount;
} else {
alert('Too high!');
}
}
}
jsFiddle.

Categories

Resources