2015-05-13 2 views
0

Цель: подтвердить эту форму. http://jsbin.com/buwejurexa/1/ Код нижеПроверяющая функция, написанная на javaScript, выполняется только один раз?

Показать все ошибки сразу, когда он нажимает кнопку «Сохранить продукт» и ошибки на каждом шаге.

Что сделано: писал проверяющий функцию ReturnVal(), который вложен в другой функции, называемой displayStorage.

Что работает: Поскольку страница загружает пользователя, нажимает кнопку «Сохранить продукт», и функция проверки правильности работает впервые. Я вижу предупреждение.

Проблема начинается, когда:

  • Пользователь выбирает категорию и продукты и видит Wattage. Это время, когда он решает нажать «Сохранить продукт». Ничего не произошло. Нет Валидации отображаются шаг за шагом.

  • Нет в консоли ошибок, но не получил ошибку в JS Bin, что (строка 253: Ожидаемое условное выражение и вместо этого увидел задание Line 258:.. Недоступен «возвращение» после «возвращения»)

Мое предположение: a) У моего оператора if и else что-то отсутствует. Я пробовал называть его из разных функций, но не повезло.

b) Четыре кнопки используют JQuery. поэтому я предполагаю, что мне нужно вызвать функцию javascript returnVal() внутри JQuery. Как это сделать. Я ссылался на 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> 
 
\t \t <select id="dd1" name="dd1" onchange="populateProducts(this,document.getElementById('products'))" required> 
 
\t \t \t <option value="select">Select-a-Category</option> 
 
\t \t \t <option value="refrigerators">Refrigerators</option> 
 
\t \t \t <option value="dishWasher">DishWasher</option> 
 
\t \t \t </select> 
 
\t \t </span> 
 
     </br> 
 

 
     <span class="placeholderText">Select a Product</span> 
 
     <span> 
 
\t \t <select id="products" onchange="populateWattage(this)" required> 
 
\t \t \t \t <option value="select" selected>--------------------------</option> 
 
\t \t </select> 
 
\t \t </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>

+3

Поместите код в вопросе (и, возможно, в скрипку, но SO поддерживает фрагменты). –

+0

@dystroy: спасибо. добавлен код. –

+2

Посмотрите на строку JSBin указывает на: 'if (missingFields = true)' обратите внимание, что '=' и '==' - два очень разных оператора. –

ответ

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? 
+0

Спасибо. Я написал только несколько функций. Сожалею. Когда я написал это, я подумал - после того, как я проверил все поля, если есть какие-либо недостающие поля, покажите мне, что предупреждение еще не отображается. –

+0

if (missingFields === true) { \t \t \t \t alert («Прежде чем продолжить, предоставьте следующие поля: \ n" + strFields); \t \t \t \t \t return false; \t \t \t \t} \t \t \t \t еще { возвращающие; } –

+0

это тоже не работает. Мои проверки не проходят –

Смежные вопросы