goal : is to validate this form. http://jsbin.com/buwejurexa/1/ Code is below
Show the user all errors at once when he clicks Save Product button and errors at each step also.
What is done : Wrote a validating function returnVal() which is nested inside another function called displayStorage.
What works : As the page loads the user clicks the Save Product button and the validating function seems to be working first time. I can see the alert.
The issue starts when :
The user selects the Category and Products and sees Wattage. This time he decides to click on Save Product. Nothing happens. No Validations are displayed step by step.
No errors in Console but got a error in JS Bin that (Line 253: Expected a conditional expression and instead saw an assignment. Line 258: Unreachable 'return' after 'return'.)
My guess : a) my if and else statement is missing something. I tried calling it from different functions but no luck.
b) The four buttons use Jquery. so I am guessing do I need to call javascript function returnVal() inside Jquery. How do I do that. I did reference the 4 buttons in my validating function.
can some help me get the validations right.
Thanks!!
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>
In the last statements of your function, there are two mistakes:
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.