簡體   English   中英

用JavaScript編寫的驗證函數只能運行一次?

[英]Validating function written in javaScript runs only once?

目標 :是驗證此表格。 http://jsbin.com/buwejurexa/1/代碼如下

單擊用戶“保存產品”按鈕時,立即向用戶顯示所有錯誤,並且在每個步驟中也向用戶顯示錯誤。

做什么 :寫了一個驗證函數returnVal(),該函數嵌套在另一個名為displayStorage的函數中。

起作用的方法 :在頁面加載時,用戶單擊“保存產品”按鈕,並且驗證功能似乎第一次起作用。 我可以看到警報。

問題從以下時間開始出現

  • 用戶選擇類別和產品,然后看到瓦數。 這次,他決定單擊“保存產品”。 什么都沒發生。 不會逐步顯示任何驗證。

  • 在Console中沒有錯誤,但是在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> 

在函數的最后一個語句中,有兩個錯誤:

  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?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM