can't get the variable taxRate to be seen in the function called by the following form. blargh! :P
here's the HTML:
<form name="incomeRange" id="incomeRange" title="Taxable Income Ranges">
<legend>Income Range:</legend>
<p name="incomeTable" id="incomeTable">
please make a selexion: <br>
<label>
<input type="radio" name="B" id="B_1" value="200" onChange="var taxRate = (this.value);">200
</label>
</p>
</form>
<form name="userAmount" id="userAmount">
<p>Target Amount to Spend:
<input type="text" name="userTargetAmount" id="userTargetAmount" onKeyUp="doTheMath(this.value);">
</p>
</form>
and the function it calls:
function doTheMath(amount)
{
var targAmt = document.getElementById("targetAmount");
var taxAmt = document.getElementById("taxAmount");
var totTaxEarn = document.getElementById("totalTaxedEarnings");
var taxRt = document.getElementById("taxRate");
console.log(amount);
console.log(taxRate);
if (!isNaN(amount))
{
targAmt.innerHTML = amount;
totTaxEarn.innerHTML = amount / taxRate;
taxRt.innerHTML = taxRate;
taxAmt.innerHTML = (amount / taxRate) - amount;
}
}
guess where it explodes? taxRate is not visible from within this function. i thought that by setting it with the onChange of the radio button, this would make it accessible... but i guess not. how can i get that value into the variable such that i can be used in the doTheMath(); function?
thanks for your time. srsly. :)
WR!
PS: and this time, i'm unlikely to figure it out on my own... i've spent three hours on this one... :P
The problem is in following code:
<input type="radio" name="B" id="B_1" value="200" onChange="var taxRate = (this.value);">200
taxRate is declared with 'var' keyword makes it is visible on 'onChange' event only. Please remove 'var' keyword.
Skip the 'onchange' handler, and just get the currently selected value in doTheMath. I would do it with jQuery this way:
$('radio[name=B]:checked').val()
Related
I’m trying to get the computer to take an input from the HTML and add and multiply some number to it in Javascript. I’m from python and the variable system in Javascript makes no sense to me, so can someone please lmk what to do?
<div class = "text">How much energy do you use?</div>
<input id = "q1" type = "text" placeholder = "# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<!-- Multiply InputValue by 3 and Add 2 —->
I tried to do something with parseInt, and parseString, but it didn’t work as it would just not run.
try this, first query input value then calculate your desire numbers then alert the user,
like this <!-- Multiply InputValue by 3 and Add 2 —->
function getInputValue() {
const inputVal = document.getElementById("q1").value; //query input value
const calculatedValue = ((inputVal *3) +2); // first multiply input value with 3
// then add 2
alert(calculatedValue); // show the calculated value through an alert
};
It's not that hard. try to play with the below code. Cheers!!
<html>
<body>
<label for="insertValue">Enter Your Value:</label>
<input type="text" id="insertValue">
<button onclick="Multiply()">Multiply</button> <!-- Calling to the JS function on button click -->
<p id="answer"></p>
<!-- Always link or write your js Scripts before closing the <body> tag -->
<script>
function Multiply() {
let value = document.getElementById("insertValue").value; //get the inserted Value from <input> text box
let answer = 0;
//Your Multiplication
answer = value * 2 * 3;
//Display answer in the <p> tag and it id ="answer"
document.getElementById("answer").innerText = "Your Answer is: "+ answer;
}
</script>
</body>
</html>
Easy (to understand) Solution:
<div class="text">How much energy do you use?</div>
<input id="q1" type="text" placeholder="# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<br>
<output id="a1"></output>
<script>
var input = document.getElementById("q1");
var output = document.getElementById("a1");
function getInputValue() {
output.textContent = (input.value * 3) + 2;
}
</script>
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>
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>
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>
Hello almighty internetz!
Im totally new on javascript, and i cant get the script to fetch numbers from input boxes, plus the sums together and write it out.
Have been sitting on Google for an hour now, so im asking you guys/girls for help!
http://jsfiddle.net/heWM2/5/
<form action="" id="brod">
<p>Pris per kartong
<input name="Prisperkartong" type="number" id="priskart" name="pris">
</p>
<p>Antal kartonger i leverans
<input name="Kartongilev" type="number" id="kartilev">
</p>
<input type="button" onClick="calculateTotal()" value="Räkna">
<div id="print"></div>
</form>
And the Javascript:
function getPrisperkartong() {
var Prisperkartong = parseInt(document.brod.priskart.value, 10);
if (isNaN(Prisperkartong)) return;
document.bord.priskart.value = Prisperkartong;
}
function getKartongilev() {
var Kartongilev = parseInt(document.brod.kartilev.value, 10);
if (isNaN(Kartongilev)) return;
document.bord.kartilev.value = Kartongilev;
}
function calculateTotal() {
var total = getPrisperkartong() + getKartongilev();
var divobj = document.getElementById('print');
divobj.style.display = 'block';
divobj.innerHTML = "Pris $" + total;
}
If you are accessing the input boxes through the form, you need to use the name field to identify the form as well as the input boxes. Your get functions should also return the value, not assign it back to the original input box. See this updated fiddle for a fixed, working example.
http://jsfiddle.net/heWM2/6/