javascript - Update the value property of 'costElement' to the calculated cost
问题描述
I'm stuck getting this program to work. I added a switch statement to determine the cost and I believe the rest is right I just don't know how to update cost in the text field. I checked this link and a few more but have been unable to find answers. Any guidance is appreciated thanks.
membership.html
<form action="" method="post" id="theForm">
<fieldset><legend>Create Your Membership</legend>
<p>Complete this form to calculate your membership. There's a 20% discount if you enroll for more than one year!</p>
<div><label for="type">Type</label> <select name="type" id="type" required>
<option value="basic">Basic - $10.00</option>
<option value="premium">Premium - $15.00</option>
<option value="gold">Gold - $20.00</option>
<option value="platinum">Platinum - $25.00</option>
</select></div>
<div><label for="years">Years</label><input type="number" name="years" id="years" min="1" required></div>
<div><label for="cost">Cost</label><input type="text" name="cost" id="cost" disabled></div>
<input type="submit" value="Calculate" id="submit">
</fieldset>
</form>
membership.js
function calculate() {
// Be strict:
'use strict';
// Variable to store the total cost:
var cost;
// Get a reference to the form elements:
var type = document.getElementById('type');
var years = document.getElementById('years');
// TODO Convert the year to a number:
var years = parseInt("1996");
// Check for valid data:
if (type && type.value && years && (years > 0)) {
// TODO Add a switch statement to determine the base cost using the value of "type"
switch(cost) {
case "basic":
text = "$10.00";
break;
case "premium":
text = "$15.00";
break;
case "gold":
text = "$20.00";
break;
case "platinum":
text = "$25.00";
break;
}
// TODO Update cost to factor in the number of years:
// Discount multiple years:
if (years > 1) {
cost *= .20; // 20%
}
var costElement = document.getElementById('cost');
// TODO update the value property of 'costElement' to the calculated cost
var costElement = type + years;
} else { // Show an error:
document.getElementById('cost').value = 'Please enter valid values.';
}
// Return false to prevent submission:
return false;
}
function init() {
'use strict';
// call a function named calculate() when form submitted
document.getElementById('theForm').onsubmit = calculate;
}
window.onload = init;
解决方案
you need to call value property of your input (type is also a node element, you need to use value property of it to get chosen option)
costElement.value = type.value + years;
推荐阅读
- ssl - javax.net.ssl 警告“user_canceled”是什么意思?
- javascript - 我如何使用 WPML 翻译 javascript 中的 html 文本
- python - PyPDF 超链接
- java - 颤振设置期间线程“主”错误中的异常
- javascript - 将数组中的 HTML 表格的一列设为可点击的 URL
- mysql - Phpmyadmin 不断要求输入密码
- php - 使用 where 子句删除大量数据会导致超时
- android - 授予权限后未调用 RxPermissions
- node.js - React Native 中的套接字 io
- c++ - cpp 谓词,std::move(pred)) 如何更改谓词?(条件变量wait_for)