Javascript Calculating a Form [duplicate] - javascript

This question already has answers here:
How not to refresh a page from JavaScript?
(3 answers)
Closed 6 years ago.
Please help me:
when i put this code it shows the result for only a sec before it refreshes the entire page. I havent been able to find any problems apart from it saying that calcCharterCost is not defined. I do not know what it means by that because to me it looks defined.
Thanks,
<script>
function calcCharterCost()
{
var destList = document.getElementById("destList");
var distance = destList.options[destList.selectedIndex].id;
var speedList = document.getElementById("speedList");
var gph = speedList.options[speedList.selectedIndex].id;
var speed = speedList.value;
var fuelCost = document.getElementById("fuelCost").value;
var feeOutput = document.getElementById("fee");
var time;
time = (distance / speed);
var cost;
cost = time * gph * fuelCost;
feeOutput.innerHTML = "$" + cost;
}
function validate()
{
if (isNaN(fuelCost) == true)
{
document.getElementById("error").innerHTML="Error invalid Fuel Cost";
document.myform.fuelCost.value="";
document.myform.fuelCost.focus();
}
}
</script>
<body>
<form name="myform">
<select id="destList">
<option id="28">Falmouth to Nantucket</option>
<option id="11">Falmouth to Edgartown</option>
<option id="7.6">Falmouth to Oak bluffs</option>
<option id="38">Falmouth to Newport</option>
</select>
<p/>
<select id="speedList">
<option id="18" value="14">14 kt</option>
<option id="24" value="18">18 kt</option>
<option id="30" value="20">20 kt</option>
<option id="37" value="22">22 kt</option>
</select>
<p/>
<input type="text" id="fuelCost" value="4.25" onblur="validate()"/>
<i><small><span style="color:red;" id="error" ></i></small> </span>
<p/>
<button onClick="calcCharterCost()">Calculate</button>
<p> The cost of the charter is <div id="fee">XXXX</div>
</body>

By default a button without a type will submit a form.
Either give the button a non-submit type:
<button type="button" onClick="calcCharterCost()">Calculate</button>
Or remove the form tag:
<form name="myform">
The latter seems preferable anyway, since the form tag is never closed and technically the markup is invalid. Nothing is actually using this form, so it's not needed.

You have markup errors and did not define fuelCost variable in global scope. When validate method executes, it cannot find the fuelCost variable as it is defined and used in calculate method.
I have fixed your script and markup issues. Please check out the corrected version and fiddle.
<script>
var fuelCost = 0;
function calcCharterCost() {
var destList = document.getElementById("destList");
var distance = destList.options[destList.selectedIndex].id;
var speedList = document.getElementById("speedList");
var gph = speedList.options[speedList.selectedIndex].id;
var speed = speedList.value;
fuelCost = document.getElementById("fuelCost").value;
var feeOutput = document.getElementById("fee");
var time;
time = (distance / speed);
var cost;
cost = time * gph * fuelCost;
feeOutput.innerHTML = "$" + cost;
}
function validate() {
if (isNaN(fuelCost) == true) {
document.getElementById("error").innerHTML = "Error invalid Fuel Cost";
document.myform.fuelCost.value = "";
document.myform.fuelCost.focus();
}
}
</script>
<body>
<select id="destList">
<option id="28">Falmouth to Nantucket</option>
<option id="11">Falmouth to Edgartown</option>
<option id="7.6">Falmouth to Oak bluffs</option>
<option id="38">Falmouth to Newport</option>
</select>
<p>
<select id="speedList">
<option id="18" value="14">14 kt</option>
<option id="24" value="18">18 kt</option>
<option id="30" value="20">20 kt</option>
<option id="37" value="22">22 kt</option>
</select>
</p>
<input type="text" id="fuelCost" value="4.25" onblur="validate()" />
<span style="color:red;" id="error"></span>
<button onClick="calcCharterCost()">Calculate</button>
The cost of the charter is
<div id="fee">XXXX</div>
</body>
Form tag is not needed in this scenario as it is not referenced by any other part of your code. I removed it.
Fiddle

Related

How to have access inside div element?

i am trying to create simple Rock,paper, scissor game,
but i have some case, i want to have access on div which id is firstplayer, also this div has increment function, which increases value by 1... if in form field i choose 12, an when i press "firstplayer" and it value will increase to 12, i want to console.log("you win"), i tried a lot, but it's not works, what can i do, to solve this problem?
<!-----my html---->
<form action="#">
<label for="numbers">Game up to:</label>
<select id="form" >
<option value="7" >7</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<input type="submit" id="submit">
</form>
<div>
<h4 onclick="increment()">Firstplayer</h4>
<div id="firstplayer">
</div>
</div>
///my js
const firsPlayer = document.getElementById("firstplayer");
const Form = document.getElementById("submit");
form.addEventListener("input", function(event){
event.preventDefault();
if (event.target.value==="12"){
return playerwin()
}
})
var x=0;
function increment(){
return firsPlayer.innerHTML = ++x;
}
// i tried this but it's not working
function playerwin(){
if(firsPlayer.childNodes[0].nodeValue == 12){
console.log("you win")
}
}
my code here https://codepen.io/kafka2001/pen/LYpmexe
Not exactly sure what the final result should be but please check the code below that illustrates how it could basically work. Just adapt it to your needs to obtain the desired result.
const firsPlayer = document.getElementById("firstplayer");
const select = document.getElementById("select");
var x = 0;
function increment() {
firsPlayer.innerHTML = Number(firsPlayer.innerHTML) + 1;
}
function addSelected() {
firsPlayer.innerHTML = Number(firsPlayer.innerHTML) + Number(select.value);
}
function playerwin() {
if (firsPlayer.childNodes[0].nodeValue == 12) {
console.log("you win")
}
}
<select id="select">
<option value="7">7</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<input type="button" onClick="increment();" value="Increment">
<div>
<h4 onclick="addSelected()">Firstplayer</h4>
<div id="firstplayer"></div>
</div>

javascript code doesn't display the answer of future value after I click the calculate button

I'm working on the fv calculator. However, I don't know why my JavaScript code doesn't display the answer of future value after I click the calculate button.
How could I solve this problem?
I will be appreciated if someone could offer me help, thanks.
Below is my HTML and JavaScript code.
<html>
<head>
<title>401K Future Value Calculator</title>
<script type="text/javascript" src="mpg.js"></script>
</head>
<body>
<h2>401K Future Value Calculator</h2>
<form id="calculationForm" >
<label for="periodicPayment">Yearly Investment($): </label>
<select id="yearlyInvest" name="Investment”">
<option value="1000: ">1000</option>
<option value="2000: ">2000</option>
<option value="3000: ">3000</option>
<option value="4000: ">4000</option>
<option value="5000: ">5000</option>
<option value="6000: ">6000</option>
<option value="7000: ">7000</option>
<option value="8000: ">8000</option>
<option value="9000: ">9000</option>
<option value="10000: ">10000</option>
</select><br><br>
<label for="annunalInterest">Annual Interest Rate(%) </label>
<input type="text" id="annunalInterestRate"><br><br>
<label for="years">Number of Years(#) </label>
<input type="text" id="numOfYears"><br><br>
<label for="future">Future Value($) </label>
<p id="futureValue">
</p>
<input type="button" id="calculate" value="Calculate">
<input type="button" onclick="clearButton()" id="clear" value="Clear">
</form>
</body>
</html>
function processForm() {
var r, n, p;
r = parseFloat(document.getElementById("annunalInterestRate").value);
n = parseInt(document.getElementById("numOfYears").value);
p = document.getElementById("yearlyInvest").value;
if (isNaN(r)) {
alert("Pleas enter a valid number.");
} else if (isNaN(n)) {
alert("Pleas enter a valid number.");
} else {
var fv = P * ((Math.pow((1 + r), n) - 1) / r);
}
document.getElementById("calculate").value;
document.getElementById("futureValue").innerHTML = fv.toFixed(2);
};
window.onload = function() {
document.getElementById("calculate").onclick = processForm;
};
function clearButton() {
document.getElementById("calculationForm").reset();
}
The way you've written your <option> nodes in the <select> contain an unnecessary : in the value= param. This is causing p to compute as NaN. Instead, rewrite as:
<select id="yearlyInvest" name="Investment”">
<option value="1000">1000</option>
<option value="2000">2000</option>
...
</select>

Javascript and HTML - Getting value from a SPAN and Selection [duplicate]

This question already has answers here:
Get selected option text with JavaScript
(16 answers)
Closed 4 years ago.
I am fairly new to Javascript programming. I would like to get the selected value from the list of values presented to the customer. I want to display this as a simple text saying, the selection was from the options provided. Let me paste the code snippet
<span id="Step2" style="display:none">
<form>
<fieldset>
<legend>Type of Customization</legend>
<p>
<label>Available Customization</label>
<select id = "myCust">
<option value = "1">New Dimension Table</option>
<option value = "2">Add a Fact Table</option>
<option value = "3">Completely New Form</option>
<option value = "4">Edit an Old Form</option>
<option value = "5">Others</option>
</select>
</p>
</fieldset>
</form>
so from the provided options, if the person chooses, say, "Completely New Form" I would like to display that into the HTML
I tried
document.getElementById("myCust")
but that won't work.
function getCust() {
var typeofCust = document.getElementById("myCust");
var cust = typeofCust.querySelector('option[value="'+typeofCust.value+'"]');
document.getElementById('selected-customer').innerText=cust.innerText;
}
document.getElementById('myCust')
.addEventListener('change', getCust)
<div id="FooterTableStep2" style="background-color:Silver">
Selected Customization : <span id="selected-customer"></span>
</div>
<form>
<fieldset>
<legend>Type of Customization</legend>
<p>
<label>Available Customization</label>
<select id="myCust">
<option value="1">New Dimension Table</option>
<option value="2">Add a Fact Table</option>
<option value="3">Completely New Form</option>
<option value="4">Edit an Old Form</option>
<option value="5">Others</option>
</select>
</p>
</fieldset>
</form>
getElementById returns the actual HTML element object.
const selectEl = document.getElementById('myCust');
const customer = selectEl.value;
console.log(customer); // selected value
It's also worth noting that most elements can also query their children
const row = document.querySelector('td:nth-child(13)');
const selectEl = row.getElementById('some-id');
Updated to include your comment:
<td id="FooterTableStep2" style="background-color: silver;">
Selected Customization: <span id="selected-customer"></span>
</td>
<script>
function getCust() {
var typeofCust = document.getElementById("myCust");
var cust = typeofCust.querySelector('option[value="' + typeofCust.value + '"]');
document.getElementById('selected-customer').innerText = cust.innerText;
}
</script>

Why does the page keep refreshing itself when the button is clicked? (JavaScript & HTML)

My friend and I are trying to make a basic interest calculator. We are assuming the starting month and year are the current month and year. When we click the button, the page refreshes and all data is lost. Any help would be greatly appreciated.
<html>
<head>
<script type="text/javascript">
function submit() {
//gets the form from the page
var form = document.getElementById("form");
//get outputs
var interest = form.elements.interest;
var total = form.elements.total;
//inputs
var principal = parseInt(form.elements.principal.value);
var rate = parseInt(form.elements.rate.value)/100/12;
var date = new Date();
var startMonth = date.getMonth()+1;
var startYear = date.getFullYear();
var endYear = parseInt(form.elements.year.value);
var endMonth = parseInt(form.elements.month.value);
var yearElapsed = endYear - startYear;
if(startMonth > endMonth)
{
endMonth+=12;
endYear--;
}
var monthsElapsed = endMonth - startMonth + (yearElapsed*12);
var months = 0;
while (months < monthsElapsed)
{
interest = (principal+interest)*(rate);
months++;
}
interest.value = interest;
total.value = interest+principal;
}
</script>
</head>
<body>
<form id="form">
Principal:
<input name="principal" type="number" value="0" />
Rate:
<input name="rate" type="number" value="0" />
End Month:
<select name="month">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
End Year:
<input name="year" type="number" value="0" />
<button type="button" onclick="submit(); return false;">Submit</button>
<br />Interest:
<output name="interest" for="rate principal month"> 0 </output>
<br />Total due:
<output name="total" for="rate principal month"> 0 </output>
</form>
</body>
</html>
That's because you're NOT stopping the default action of that button (in this case is to submit that form). Once your submit() in JS is executed, browser is proceeding with form submission. As there's no action attribute defined on your <form> element, browser will simply post your data to the same URL which results in a full page refresh. After the page refresh, any data entered is lost.
You can stop the default action by passing the event object to your click handler like below
<button type="button" onclick="submit(event);">Submit</button>
Then in your event handler function, you can call event's preventDefault() method.
function submit(event) {
event.preventDefault();
}
Create attribute on form tag onsubmit,
onsubmit="return submit();"
Remove button Submit and add
and at the end of your submit function return false
return false;
and everything will be ok.

Count and Display Combined Select Option Values

How would you check the combined sum of select option values and display them in another input using javascript?
<form>
<select id="first">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="second">
<option value="3">3</option>
<option value="4">4</option>
</select>
<input value="combined sum of select value for id='first', id='second'" type="number">
</form>
Yes, Google is a good idea to find what you're looking for.
Look for a Javascript basics and a jQuery tutorial.
I can recommend Codeschool, they are having very good free online courses for these topics. (Sign-up required but there are many free courses.) The courses are fun to do. They are structured in short video screencasts and afterwards you have to use that knowledge to pass the exercise.
And if you're stuck at some point there are always good hints to solve the exam.
What you are looking for will be something like the script below.
To select the option you can use $('#first').val() and to track changes you will use event handlers for the change event $('#first').on('change', function(){ ... }.
var adder = (function($){
var first = 0;
var second = 0;
var init = function() {
first = getOption('#first');
second = getOption('#second');
var result = add(first,second);
//console.log(result); // for debugging in console of browser
update(result);
//console.log(first,second);
};
var getOption = function(selector) {
return parseInt($(selector).val());
};
var add = function(a,b) {
return a+b;
};
var update = function(value) {
$("#result").val(value);
};
// event handlers
$('#first').on('change', function(){
first = getOption('#first');
update(add(first,second));
});
$('#second').on('change', function(){
second = getOption('#second');
update(add(first,second));
});
return {init:init};
})(jQuery);
$(function() {
// Handler for .ready() called.
adder.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="first">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="second">
<option value="3">3</option>
<option value="4">4</option>
</select>
<input id="result" value="combined sum of select value for id='first', id='second'" type="number"/>
</form>
The below code will add HTML elements together using JavaScript.
<input type="number" id="first" value="1"></input>
<input type="number" id="second" value="2"></input>
<button onclick="counter()">add</button>
<p id="display"></p>
<script>
function counter() {
var first = Number(document.getElementById("first").value);
var second = Number(document.getElementById("second").value);
var x = first + second;
document.getElementById("display").innerHTML = x;
}
</script>

Categories