Reputation: 12487
I had some code that was working just fine. However, now I am trying to make it so that the pricecalc is recalculated every time the user selects a different option from the select field. Now I get an undefined error in console.
function pricecalc() {
var a = document.getElementById("field_0");
var quantity = a.value.substring(0, 1);
var b = document.getElementById("field_1");
var type = b.value;
if (quantity == '2') {
var rate = '120';
} else if (quantity == '3') {
var rate = '110';
} else {
var rate = '100';
}
var price = rate * quantity;
if (type == 'Credit card') {
var price = price * 1.034;
}
var price_each = (price / quantity);
var redirect = 'https://www.paypal.me/' + price;
document.getElementById("cost").innerHTML = '£' + price;
document.getElementById("costeach").innerHTML = '£' + price_each;
}
This is the HTML
<select name='field_0' id='field_0' class='text_select' onchange="pricecalc()">
<option value="2 people">2 people</option>
<option value="3 people">3 people</option>
<option value="4 people">4 people</option>
<option value="5 people">5 people</option>
<option value="6 people">6 people</option>
</select>
<select name='field_1' id='field_1' class='text_select' onchange="pricecalc()">
<option value="Bank transfer">Bank transfer</option>
<option value="Debit card">Debit card</option>
<option value="Credit card">Credit card</option>
</select>
<h4>
<b>Total Price</b>
<span id="cost">Hello World!</span>
<b>Price Each</b>
<span id="costeach">Hello World!</span>
</h4>
I'm fairly certain this is just an issue with the fact I have put it in a function because outside of a function it works fine. Could anyone please help me understand why my approach to putting it in a function that updates when the select selection is updated is failing?
Here is a link to try it: https://jsfiddle.net/spadez/gwoss8L1/2/
Upvotes: 0
Views: 71
Reputation: 31024
Its a jsfiddle config thing.
In the js menu change "Load Type" to:
No wrap - in <body>
"
It was set to onLoad
so i guess the function wasn't created yet.
Upvotes: 4