目标:是验证此表单。 http://jsbin.com/buwejurexa/1/ 代码如下
当用户点击每个步骤中的“保存产品”按钮和错误时,立即向用户显示所有错误。
做了什么: 写了一个验证函数returnVal(),它嵌套在另一个名为displayStorage的函数中。
什么有用: 当页面加载时,用户单击“保存产品”按钮,验证功能似乎第一次正常工作。我可以看到警报。
问题从:
开始用户选择类别和产品并看到瓦数。这个 他决定点击保存产品的时间。什么都没发生。没有 验证逐步显示。
在控制台中没有错误但在JS Bin中出现错误(第253行:预期条件表达式,而是看到了一个赋值。 第258行:“返回”后无法访问“返回”。)
我的猜测: a)我的if和else语句缺少某些东西。我尝试从不同的功能调用它,但没有运气。
b)四个按钮使用Jquery。所以我猜我是否需要在Jquery中调用javascript函数returnVal()。我怎么做。我确实参考了验证功能中的4个按钮。
可以帮助我正确验证。
谢谢!
var wattage = {
'Artic King AEB': 100,
'Artic King ATMA': 200,
'Avanti Compact': 300,
'Bosch SS': 400,
'Bosch - SHXUC': 100,
'Asko DS': 200,
'Blomberg': 300,
'Amana': 400
};
var annualEnergy = 0;
var dailyEnergyConsumed = 0;
function populateProducts(category, products) {
var refrigerators = new Array('Artic King AEB', 'Artic King ATMA', 'Avanti Compact', 'Bosch SS');
var dishWasher = new Array('Bosch - SHXUC', 'Asko DS', 'Blomberg', 'Amana');
switch (category.value) {
case 'refrigerators':
products.options.length = 0;
for (i = 0; i < refrigerators.length; i++) {
createOption(products, refrigerators[i], refrigerators[i]);
}
break;
case 'dishWasher':
products.options.length = 0;
for (i = 0; i < dishWasher.length; i++) {
createOption(products, dishWasher[i], dishWasher[i]);
}
break;
default:
products.options.length = 0;
break;
}
populateWattage(products);
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
function populateWattage(product) {
document.getElementById('wattage').innerText = wattage[product.value];
populateStorage();
}
function setConsumption(hrs) {
setConsumption();
}
dailyEnergyConsumption = function(hrs) {
dailyEnergyConsumed = 0;
dailyEnergyConsumed = parseFloat(hrs * parseInt(document.getElementById('wattage').innerText) / 1000).toFixed(2);
document.getElementById('dailyEnergyConsumptionVal').innerText = dailyEnergyConsumed + " kWh";
populateStorage();
};
annualEnergyConsumption = function(days) {
annualEnergy = 0;
var allYear = document.getElementById('allYear');
var halfYear = document.getElementById('halfYear');
var threeMonths = document.getElementById('threeMonths');
var oneMonth = document.getElementById('oneMonth');
if (allYear || days != 365) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
} else if (days == 182 && !halfYear) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
} else if (days == 90 && !threeMonths) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
} else if (days == 30 && !oneMonth) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
}
populateStorage();
};
// code that shows which button is clicked. Green div below the 4 buttons
$(document).ready(function() {
$("#h1").click(function() {
$("#onesSelected").show();
$("#threeSelected").hide();
$("#sixSelected").hide();
$("#twentyFourSelected").hide();
});
$("#h3").click(function() {
$("#threeSelected").show();
$("#onesSelected").hide();
$("#sixSelected").hide();
$("#twentyFourSelected").hide();
});
$("#h6").click(function() {
$("#sixSelected").show();
$("#onesSelected").hide();
$("#threeSelected").hide();
$("#twentyFourSelected").hide();
});
$("#h24").click(function() {
$("#twentyFourSelected").show();
$("#onesSelected").hide();
$("#threeSelected").hide();
$("#sixSelected").hide();
});
});
function compareSetup() {
var prodName = localStorage.getItem('productKey');
var energyName = parseInt(localStorage.getItem('energyKey'), 10);
var useName = parseInt(localStorage.getItem('estimatedUse'), 10);
return false;
}
function populateStorage() {
var productBox = document.getElementById("products");
var productName = productBox.options[productBox.selectedIndex].text;
localStorage.setItem('productKey', productName);
localStorage.setItem('energyKey', document.getElementById("annualEnergyConsumption").innerHTML);
//localStorage.setItem.querySelector('input[id="usageRadio"]:checked').value;
//localStorage.setItem('usageRadio' + $(this).attr('id'), JSON.stringify({ checked: this.checked }));
//localStorage.setItem('estimatedUse', document.getElementById("usageRadio"));
// do other things if necessary
}
function displayStorage() {
var displayProduct = document.getElementById("displayName");
var displayAnnual = document.getElementById("displayAnnual");
displayProduct.innerHTML = "Selected Product: " + localStorage.getItem('productKey');
displayProduct.style = "display:inline;";
displayAnnual.innerHTML = "Annual Consumption: " + localStorage.getItem('energyKey');
returnVal();
}
//validation code starts here
function returnVal() {
//initialize the form elements starting from form name , category and product dropdown, daily use buttons and finally the radio buttons
var energyForm = document.getElementsByName("energyForm")[0];
// drop downs
var catDropdown = document.getElementById("dd1");
var prodDropdown = document.getElementById("products");
// call the 4 Daily use button
var notLotButton = document.getElementById("h1");
var averageButton = document.getElementById("h3");
var lotButton = document.getElementById("h6");
var alwaysButton = document.getElementById("h24");
// radio button group
var allYearRadio = document.getElementById("allYear");
var halfYearRadio = document.getElementById("halfYear");
var threeMonthsRadio = document.getElementById("threeMonths");
var oneMonthRadio = document.getElementById("oneMonth");
//
var missingFields = false;
var strFields = "";
if (catDropdown.selectedIndex === 0) {
missingFields = true;
strFields += "Select Category and the related Product \n";
catDropdown.focus();
} else {
return true;
}
if ((!notLotButton.clicked) &&
(!averageButton.clicked) &&
(!lotButton.clicked) &&
(!alwaysButton.clicked)) {
missingFields = true;
strFields += "Select atleast one Estimated Daily Use option \n";
} else {
return true;
}
if ((!allYearRadio.checked) &&
(!halfYearRadio.checked) &&
(!threeMonthsRadio.checked) &&
(!oneMonthRadio.checked)) {
missingFields = true;
strFields += "Select atleast one Estimated Yearly Use option \n";
} else {
return true;
}
if (missingFields = true) {
alert("Please provide the following fields before continuing: \n" + strFields);
}
return false;
return true;
}
function resetForm() {
document.getElementById("resetButton");
document.getElementById("energyForm").reset();
document.getElementById('products').value = "select";
//document.getElementById('select_value').selectedIndex = 3;
}
#leftColumn {
width: 600px;
float: left;
}
.placeholderText {
font: bold 12px/30px Georgia, serif;
}
body {
padding-left: 45px;
}
#annualEnergyConsumption {
font: bold 25px arial, sans-serif;
color: #00ff00;
}
#dailyEnergyConsumptionVal {
font: bold 25px arial, sans-serif;
color: #00ff00;
}
#annualCostOperation {
font: bold 40px arial, sans-serif;
color: #00ff00;
}
.dailyButInline {
display: inline;
}
#wattage {
position: absolute;
left: 160px;
top: 130px;
font: bold 25px arial, sans-serif;
color: #00ff00;
}
/* mouse over link */
button:hover {
background-color: #b6b6b6;
}
#onesSelected {
position: absolute;
left: 53px;
top: 246px;
background-color: #00ff00;
display: none;
width: 99px;
height: 5px;
}
#threeSelected {
position: absolute;
left: 156px;
top: 246px;
background-color: #00ff00;
display: none;
width: 99px;
height: 5px;
}
#sixSelected {
position: absolute;
left: 259px;
top: 246px;
background-color: #00ff00;
display: none;
width: 99px;
height: 5px;
}
#twentyFourSelected {
position: absolute;
left: 362px;
top: 246px;
background-color: #00ff00;
display: none;
width: 113px;
height: 5px;
}
#store {
cursor: pointer;
}
<h2>Annual Energy Consumption and Cost Calculator</h2>
<form id="energyForm" onSubmit="return compareSetup()" action="" method="post">
<div id="leftColumn">
<div>
<span class="placeholderText">Choose Category</span>
<span>
<select id="dd1" name="dd1" onchange="populateProducts(this,document.getElementById('products'))" required>
<option value="select">Select-a-Category</option>
<option value="refrigerators">Refrigerators</option>
<option value="dishWasher">DishWasher</option>
</select>
</span>
</br>
<span class="placeholderText">Select a Product</span>
<span>
<select id="products" onchange="populateWattage(this)" required>
<option value="select" selected>--------------------------</option>
</select>
</span>
</div>
<div>
<span class="placeholderText">Wattage</span>
<span id="wattage">0</span>
</br>
</br>
</div>
<div id="buttonBoundary">
<div class="placeholderText">Estimated Daily Use</div>
<div class="dailyButInline">
<button type="button" id="h1" onclick="dailyEnergyConsumption(1)">Not a Lot</br>1 hour per day</button>
</div>
<div class="dailyButInline">
<button type="button" id="h3" onclick="dailyEnergyConsumption(3)">Average</br>3 hour per day</button>
</div>
<div class="dailyButInline">
<button type="button" id="h6" onclick="dailyEnergyConsumption(6)">A Lot</br>6 hour per day</button>
</div>
<div class="dailyButInline">
<button type="button" id="h24" onclick="dailyEnergyConsumption(24)">Always On</br>24 hours per day</button>
</div>
<div id="onesSelected"></div>
<div id="threeSelected"></div>
<div id="sixSelected"></div>
<div id="twentyFourSelected"></div>
</br>
</br>
</div>
<div>
<span class="placeholderText">Daily Energy Consumption</span>
</br>
<div id="dailyEnergyConsumptionVal">---</div>
</br>
</div>
<div>
<span class="placeholderText">Estimated Yearly Use</span>
</br>
<input type="radio" name="usageRadio" value="365" id="allYear" onclick="annualEnergyConsumption(365)" />
<label for="allYear">All year</label>
<input type="radio" name="usageRadio" value="182" id="halfYear" onclick="annualEnergyConsumption(182)" />
<label for="halfYear">6 Months</label>
<input type="radio" name="usageRadio" value="90" id="threeMonths" onclick="annualEnergyConsumption(90)" />
<label for="threeMonths">3 Months</label>
<input type="radio" name="usageRadio" value="30" id="oneMonth" onclick="annualEnergyConsumption(30)" />
<label for="oneMonth">1 Month</label>
<!-- <div id="daysUsed"><input type="number" id="hour" maxlength="2" min="1" onchange="annualEnergyConsumption(this.value)"></br> -->
</div>
</br>
<div>
<span class="placeholderText">Energy Consumption</span>
</br>
<div id="annualEnergyConsumption">---</div>
</br>
</div>
<input type="submit" value="Save Product" onclick="displayStorage()" />
<input type="reset" onclick="resetForm()" id="resetButton" value="Reset" />
</div>
<div id="right">
<div id="displayName">Selected Product:</div>
<div id="displayAnnual">Annual Consumption:</div>
</div>
</form>
答案 0 :(得分:1)
在你的函数的最后一个陈述中,有两个错误:
if (missingFields = true) { // should be: missingFields == true
alert("Please provide the following fields before continuing: \n" + strFields);
}
return false;
return true; // You already returned false; did you mean to return false inside the if?