我正在开发一种功能,允许根据用户对表单的输入自动计算订单的价格。用户将选择他们想要的“类型”服务,并且还输入订单的“平方英尺”。
问题是因为我试图将字符串变量设置为具有intiger值吗?
当我按下表格上的按钮时,网页上没有任何内容。
<form>
<select id="type" required>
<option disabled selected value> Type of service </option>
<option value="Gardening">Gardening</option>
<option value="Decorating">Decorating</option>
<option value="Fencing">Fencing</option>
<option value="Flooring">Flooring</option>
<option value="Landscaping">Landscaping</option>
</select>
<input type="number" id="square_ft" placeholder="square_ft">
<button type="submit" onclick="calculatePrice()">Check Price</button>
</form>
<p id="price"> </p>
<script>
function calculatePrice() {
var hours = 4;
var totalPriceHour = 0;
var priceHour = 0;
var priceSquareFt = 0;
var totalSquareFt = 0;
var orderTotal = 0;
var materials = false;
var type = document.getElementById("type").value;
var square_ft = document.getElementById("square_ft").value;
if (type == Gardening) {
priceHour = 20;
priceSquareFt = 3;
} else if (type == Decorating) {
priceHour = 20;
priceSquareFt = 3;
} else if (type == Landscaping) {
priceHour = 30;
priceSquareFt = 2;
} else if (type == Flooring) {
priceHour = 20;
priceSquareFt = 2;
} else (type == Fencing) {
priceHour = 30;
priceSquareFt = 3;
}
totalPriceHour = hours * priceHour;
totalSquareFt = square_ft * priceSquareFt;
orderTotal = totalSquareFt + totalPriceHour;
document.getElementById("price").innerHTML = orderTotal;
}
</script>
答案 0 :(得分:0)
输入的值将返回一个字符串,因此请确保将您的类型变量与为验证添加引号的字符串进行比较...如果您在表单中放置一个提交按钮,则会尝试向服务器..
function calculatePrice() {
var hours = 4;
var totalPriceHour = 0;
var priceHour = 0;
var priceSquareFt = 0;
var totalSquareFt = 0;
var orderTotal = 0;
var materials = false;
var type = document.getElementById("type").value;
var square_ft = document.getElementById("square_ft").value;
if (type == 'Gardening') {
priceHour = 20;
priceSquareFt = 3;
} else if (type == 'Decorating') {
priceHour = 20;
priceSquareFt = 3;
} else if (type == 'andscaping') {
priceHour = 30;
priceSquareFt = 2;
} else if (type == 'Flooring') {
priceHour = 20;
priceSquareFt = 2;
} else if (type == 'Fencing') {
priceHour = 30;
priceSquareFt = 3;
}
totalPriceHour = hours * priceHour;
totalSquareFt = square_ft * priceSquareFt;
orderTotal = totalSquareFt + totalPriceHour;
document.getElementById("price").innerHTML = orderTotal;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="type" required>
<option disabled selected value> Type of service </option>
<option value="Gardening">Gardening</option>
<option value="Decorating">Decorating</option>
<option value="Fencing">Fencing</option>
<option value="Flooring">Flooring</option>
<option value="Landscaping">Landscaping</option>
</select>
<input type="number" id="square_ft" placeholder="square_ft">
<button type="button" onclick="calculatePrice()">Check Price</button>
</form>
<p id="price"> </p>
&#13;