Having trouble using local storage for css toggle switch - javascript
Snippet:
/* LOCAL STORAGE */
const searchUser=document.getElementById('autocomplete');
const messageUser=document.getElementById('message-user');
const timezone=document.getElementById('timezone');
const send=document.querySelector('.send');
const save=document.querySelector('.save');
const switch1=document.querySelectorAll('input[type="checkbox]')[0];
const switch2=document.querySelectorAll('input[type="checkbox]')[1];
send.addEventListener('click', function() {
if (searchUser.value && messageUser.value) {
localStorage.setItem("user",searchUser.value);
localStorage.setItem("message",messageUser.value);
window.alert("Your settings have been saved to local storage");
location.reload();
} else if (searchUser.value || messageUser.value) {
window.alert("Please fill in all required fields");
}
});
save.addEventListener('click', function() {
if (timezone.value) {
localStorage.setItem("timezone",timezone.value);
localStorage.setItem("switch1", switch1.checked);
localStorage.setItem("switch2", switch2.checked);
window.alert("Your settings have been saved to local storage");
location.reload();
}
});
/* MESSAGE USERS */
/* SETTINGS */
.message-users,
.settings {
display: flex;
flex-direction: column;
padding: 0 15px;
border-top: 1px grey solid;
}
.settings {
border-left: 1px grey solid;
}
.message-users > * {
padding: 5px;
margin-bottom: 10px;
}
.settings > * {
margin-bottom: 10px
}
.settings > label {
padding: 10px 0;
}
select[id="timezone"] {
margin-top: auto;
padding: 10px;
}
.settings-buttons {
width: 100%;
display: flex;
justify-content: space-between;
}
.save,
.cancel {
flex-basis: 48%;
}
.button {
color: white;
background-color: #7279C2;
padding: 5px;
}
.cancel {
background-color: #B2B2B2;
}
<!-- MESSAGE USERS -->
<section class="message-users section">
<h2>Message User</h2>
<input type="search" id="autocomplete" tabindex="1" placeholder="Search for User">
<textarea id="message-user" rows="10" cols="50" placeholder="Message for User"></textarea>
<button class="button send">Send</button>
</section>
<!-- SETTINGS -->
<section class="settings section">
<h2>Settings</h2>
<label class="switch-light switch-ios" onclick="">
<input type="checkbox">
<strong class="switch-light-text">
Send Email Notifications
</strong>
<span class="switch-light-span">
<span>Off</span>
<span>On</span>
<a></a>
</span>
</label>
<label class="switch-light switch-ios" onclick="">
<input type="checkbox">
<strong class="switch-light-text">
Set Profile to Public
</strong>
<span class="switch-light-span">
<span>Off</span>
<span>On</span>
<a></a>
</span>
</label>
<select id="timezone">
<option value="volvo" selected>Select a Timezone</option>
<option value="volvo">Volvo</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<div class="settings-buttons">
<button class="button save">Save</button>
<button class="button cancel">Cancel</button>
</div>
</section>
I want to check the timezone value, and the two toggle on/off buttons and then output the alert "your settings have been saved to local storage. I know I have to save toggle buttons state as checked, and I researched similar questions on stack, but nothing seems to work.
The second paragraph of code is the one I am working one.
found console error on:
document.querySelectorAll('input[type="checkbox]') , [0] and [1].
this should be :
document.querySelectorAll('input[type=checkbox]').
( without double quote.
(console is on F12 of every browser)
and also :
else if (searchUser.value || messageUser.value) .
should be:
else if (searchUser.value=='' || messageUser.value=='')
Local storage values are also visible in the browser inspector (F12), in the storage part
conplete JS:
/* LOCAL STORAGE */
const searchUser = document.getElementById('autocomplete')
, messageUser = document.getElementById('message-user')
, timezone = document.getElementById('timezone')
, send = document.querySelector('.send')
, save = document.querySelector('.save')
, switch1 = document.querySelectorAll('input[type=checkbox]')[0]
, switch2 = document.querySelectorAll('input[type=checkbox]')[1]
;
send.addEventListener('click', function ()
{
if (searchUser.value && messageUser.value)
{
localStorage.setItem("user", searchUser.value);
localStorage.setItem("message", messageUser.value);
window.alert("Your settings have been saved to local storage");
location.reload();
}
else if (searchUser.value=='' || messageUser.value=='')
{
window.alert("Please fill in all required fields");
}
});
save.addEventListener('click', function ()
{
if (timezone.value) {
localStorage.setItem("timezone", timezone.value);
localStorage.setItem("switch1", switch1.checked);
localStorage.setItem("switch2", switch2.checked);
window.alert("Your settings have been saved to local storage");
location.reload();
}
});
Related
How to match user input with array data in JavaScript
I'm new in learning HTML, JavaScript and CSS. I'm stuck at this JavaScript code. I'm trying to match user input on the searchbar with some city array list I already prepared, when the search result match the script will change the display style of element into showing the result of their search value, but until now the result always showing false value. Is there any better way to do this? Is there something wrong with my code? function searchRespond() { if (document.getElementById("myInput").value.match(cities)) { document.getElementById("areaCovered").style.display = "block"; } else { document.getElementById("areaNotCovered").style.display = "block"; document.getElementById("searchResult").innerHTML = document.getElementById("myInput").value; } } var cities = ["Banda Aceh", "Bandar Lampung", "Banyuwangi", "Bandung", "Bali", "Batam", "Batu", "Bekasi", "Bengkulu", "Binjai", "Blitar", "Bogor", "Bukittinggi", "Cimahi", "Cirebon", "Denpasar", "Depok", "Dumai", "Gunungsitoli", "Jakarta", "Jambi", "Kediri", "Langsa", "Lhokseumawe", "Lombok", "Lubuklinggau", "Madiun", "Magelang", "Malang", "Medan", "Metro", "Mojokerto", "Padang", "Padang Sidempuan", "Padangpanjang", "Pagar Alam", "Palembang", "Pangkal Pinang", "Pariaman", "Pasuruan", "Payakumbuh", "Pekalongan", "Pekanbaru", "Pematangsiantar", "Prabumulih", "Prigi", "Probolinggo", "Sabang", "Salatiga", "Sawahlunto", "Semarang", "Serang", "Sibolga", "Solo", "Subussalam", "Sukabumi", "Sumbawa", "Sungaipenuh", "Surabaya", "Surakarta", "Tangerang", "Tangerang Selatan", "Tanjungbalai", "Tanjungpinang", "Tasikmalaya", "Tebing Tinggi", "Tegal", "Yogyakarta"]; .HeadlineSearchContainer { position: relative; top: 100px; margin: auto; height: 159px; } .SearchCharacterStyle { font-family: Roboto; font-size: 12px; line-height: 24.82px; text-align: left; } .searchrespond { font-family: Roboto; font-size: 12px; line-height: 24.82px; text-align: left; } #areaCovered { display: none; } #areaNotCovered { display: none; } #fillArea { display: none; } <div class="HeadlineSearchContainer"> <div class="SearchCharacterStyle"> <h>SEARCH FOR AREA COVERANGE</h> </div> <div id="mySearch" class="searchbox_box"> <form autocomplete="off" name="myForm"> <div class="autocomplete" style="width:300px;"> <input id="myInput" type="text" name="city" placeholder="Enter Your Destination City"> <i class="searchbutton"></i> </div> <input type="button" formtarget="_new" onclick="searchRespond()" name="input" value="Search"> <div class="searchrespond" id="searchRespond"> <h id="areaCovered">YES! We cover your area destination</h> <h id="areaNotCovered">We don't cover your area destination yet <p id="searchResult"></p> </h> <h id="fillArea">Please fill your area destination first</h> </div> </form> </div> </div>
To do what you require you can use filter() to match the user's input to values in your array. You would be best to perform a case-insensitive match, which can be done by converting both values to the same case. Note that this logic sets the notifications as hidden before the logic runs, so that the previous state of the search is removed. In addition, I made a couple of improvements to the code. Firstly I stored the relevant elements in variables instead of accessing the DOM every time. This is slightly more performant, and makes the code a lot easier to read. I also used addEventListener() to bind events instead of inline event handlers in the HTML, which are bad practice and shouldn't be used. Lastly I converted the <h> elements to <h2 /> in this demo, as there is no <h> element in HTML. const input = document.querySelector('#myInput'); const areaCovered = document.querySelector('#areaCovered'); const areaNotCovered = document.querySelector('#areaNotCovered'); const searchResult = document.querySelector('#searchResult'); const fillArea = document.querySelector('#fillArea'); const cities = ["Banda Aceh", "Bandar Lampung", "Banyuwangi", "Bandung", "Bali", "Batam", "Batu", "Bekasi", "Bengkulu", "Binjai", "Blitar", "Bogor", "Bukittinggi", "Cimahi", "Cirebon", "Denpasar", "Depok", "Dumai", "Gunungsitoli", "Jakarta", "Jambi", "Kediri", "Langsa", "Lhokseumawe", "Lombok", "Lubuklinggau", "Madiun", "Magelang", "Malang", "Medan", "Metro", "Mojokerto", "Padang", "Padang Sidempuan", "Padangpanjang", "Pagar Alam", "Palembang", "Pangkal Pinang", "Pariaman", "Pasuruan", "Payakumbuh", "Pekalongan", "Pekanbaru", "Pematangsiantar", "Prabumulih", "Prigi", "Probolinggo", "Sabang", "Salatiga", "Sawahlunto", "Semarang", "Serang", "Sibolga", "Solo", "Subussalam", "Sukabumi", "Sumbawa", "Sungaipenuh", "Surabaya", "Surakarta", "Tangerang", "Tangerang Selatan", "Tanjungbalai", "Tanjungpinang", "Tasikmalaya", "Tebing Tinggi", "Tegal", "Yogyakarta"]; document.querySelector('#search-from').addEventListener('submit', e => { e.preventDefault(); const searchTerm = input.value.trim().toLowerCase(); fillArea.style.display = 'none'; areaCovered.style.display = 'none'; areaNotCovered.style.display = 'none'; if (!searchTerm) { fillArea.style.display = 'block'; return; } let matches = cities.filter(city => city.toLowerCase() == searchTerm); if (matches.length) { areaCovered.style.display = 'block'; } else { areaNotCovered.style.display = 'block'; } }); .HeadlineSearchContainer { position: relative; top: 100px; margin: auto; height: 159px; } .SearchCharacterStyle { font-family: Roboto; font-size: 12px; line-height: 24.82px; text-align: left; } .searchrespond { font-family: Roboto; font-size: 12px; line-height: 24.82px; text-align: left; } #areaCovered { display: none; } #areaNotCovered { display: none; } #fillArea { display: none; } .autocomplete { width: 300px; } <div class="HeadlineSearchContainer"> <div class="SearchCharacterStyle"> <h>SEARCH FOR AREA COVERANGE</h> </div> <div id="mySearch" class="searchbox_box"> <form autocomplete="off" name="myForm" id="search-from"> <div class="autocomplete"> <input id="myInput" type="text" name="city" placeholder="Enter Your Destination City"> <i class="searchbutton"></i> </div> <button type="submit">Search</button> <div class="searchrespond" id="searchRespond"> <h2 id="areaCovered">YES! We cover your area destination</h2> <h2 id="areaNotCovered">We don't cover your area destination yet</h2> <h2 id="fillArea">Please fill your area destination first</h2> </div> </form> </div> </div>
You can use javascript includes(). <script> const fruits = ["Banana Aceh", "Orange", "Apple", "Mango"]; let str = "Banana Aceh"; //document.getElementById("myInput").value if(fruits.some(v => str.includes(v))) { console.log("Exists"); } else { console.log("Did not Exists"); } </script>
function searchRespond() { let searchTerm = document.getElementById("myInput").value; if (cities.find(city => city == searchTerm)) { document.getElementById("areaCovered").style.display = "block"; } else { document.getElementById("areaNotCovered").style.display = "block"; document.getElementById("searchResult").innerHTML = document.getElementById("myInput").value; } } var cities = ["Banda Aceh", "Bandar Lampung", "Banyuwangi", "Bandung", "Bali", "Batam", "Batu", "Bekasi", "Bengkulu", "Binjai", "Blitar", "Bogor", "Bukittinggi", "Cimahi", "Cirebon", "Denpasar", "Depok", "Dumai", "Gunungsitoli", "Jakarta", "Jambi", "Kediri", "Langsa", "Lhokseumawe", "Lombok", "Lubuklinggau", "Madiun", "Magelang", "Malang", "Medan", "Metro", "Mojokerto", "Padang", "Padang Sidempuan", "Padangpanjang", "Pagar Alam", "Palembang", "Pangkal Pinang", "Pariaman", "Pasuruan", "Payakumbuh", "Pekalongan", "Pekanbaru", "Pematangsiantar", "Prabumulih", "Prigi", "Probolinggo", "Sabang", "Salatiga", "Sawahlunto", "Semarang", "Serang", "Sibolga", "Solo", "Subussalam", "Sukabumi", "Sumbawa", "Sungaipenuh", "Surabaya", "Surakarta", "Tangerang", "Tangerang Selatan", "Tanjungbalai", "Tanjungpinang", "Tasikmalaya", "Tebing Tinggi", "Tegal", "Yogyakarta"]; .HeadlineSearchContainer { position: relative; top: 100px; margin: auto; height: 159px; } .SearchCharacterStyle { font-family: Roboto; font-size: 12px; line-height: 24.82px; text-align: left; } .searchrespond { font-family: Roboto; font-size: 12px; line-height: 24.82px; text-align: left; } #areaCovered { display: none; } #areaNotCovered { display: none; } #fillArea { display: none; } <div class="HeadlineSearchContainer"> <div class="SearchCharacterStyle"> <h>SEARCH FOR AREA COVERANGE</h> </div> <div id="mySearch" class="searchbox_box"> <form autocomplete="off" name="myForm"> <div class="autocomplete" style="width:300px;"> <input id="myInput" type="text" name="city" placeholder="Enter Your Destination City"> <i class="searchbutton"></i> </div> <input type="button" formtarget="_new" onclick="searchRespond()" name="input" value="Search"> <div class="searchrespond" id="searchRespond"> <h id="areaCovered">YES! We cover your area destination</h> <h id="areaNotCovered">We don't cover your area destination yet <p id="searchResult"></p> </h> <h id="fillArea">Please fill your area destination first</h> </div> </form> </div> </div>
suggest to validate input by making first letter uppercase and rest lowercase to match the array values with javascript indexOf function function searchRespond() { var input = document.getElementById("myInput").value; var area2search = input.charAt(0).toUpperCase() + input.slice(1).toLowerCase(); /* make fist letter capital and rest lower case to match array */ if (cities.indexOf(area2search) > -1) { document.getElementById("areaCovered").style.display = "block"; //In the array! } else { document.getElementById("areaNotCovered").style.display = "block"; document.getElementById("searchResult").innerHTML = document.getElementById("myInput").value; } } var cities = ["Banda Aceh", "Bandar Lampung", "Banyuwangi", "Bandung", "Bali", "Batam", "Batu", "Bekasi", "Bengkulu", "Binjai", "Blitar", "Bogor", "Bukittinggi", "Cimahi", "Cirebon", "Denpasar", "Depok", "Dumai", "Gunungsitoli", "Jakarta", "Jambi", "Kediri", "Langsa", "Lhokseumawe", "Lombok", "Lubuklinggau", "Madiun", "Magelang", "Malang", "Medan", "Metro", "Mojokerto", "Padang", "Padang Sidempuan", "Padangpanjang", "Pagar Alam", "Palembang", "Pangkal Pinang", "Pariaman", "Pasuruan", "Payakumbuh", "Pekalongan", "Pekanbaru", "Pematangsiantar", "Prabumulih", "Prigi", "Probolinggo", "Sabang", "Salatiga", "Sawahlunto", "Semarang", "Serang", "Sibolga", "Solo", "Subussalam", "Sukabumi", "Sumbawa", "Sungaipenuh", "Surabaya", "Surakarta", "Tangerang", "Tangerang Selatan", "Tanjungbalai", "Tanjungpinang", "Tasikmalaya", "Tebing Tinggi", "Tegal", "Yogyakarta"];
HTML Replace Select item with something more formatable
I have on a website a select box to select the language of the website: <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <select class="w3-bar-item w3-select w3-right w3-button" onchange="if (this.value) window.location.href=this.value" style="-webkit-appearance: none;"> <option value="?&lang=lu"<?php if ($_SESSION['lang'] == "lu") echo "selected='selected'";?>>Lëtzebuergesch</option> <option value="?&lang=en"<?php if ($_SESSION['lang'] == "en") echo "selected='selected'";?>>English</option> <option value="?&lang=fr"<?php if ($_SESSION['lang'] == "fr") echo "selected='selected'";?>>Français</option> <option value="?&lang=de"<?php if ($_SESSION['lang'] == "de") echo "selected='selected'";?>>Deutsch</option> </select> This works all fine but I cannot format it as i want. I would like to replace it with something like this: <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <div class="w3-dropdown-hover"> <button class="w3-button">Dropdown</button> <div class="w3-dropdown-content w3-bar-block w3-card-4"> Lëtzebuergesch English Français Deutsch </div> </div> So that when you chose the language it sets the value of &lang and sets the name of the button to the language that is selected. I hope someone can help me with this. You can see the select box in action here on the upper right of the site: (https://elgaucho.lu/beta/) Thanks for your help Andy
Scroll a bit to see how to make a custom select. All you need are last HTML and CSS codes. Other codes are just to implement the logic with JS (I know you did that with PHP). Standard HTML select solution. HTML: <select id="select"> <option value="?&lang=lu">Lëtzebuergesch</option> <option value="?&lang=en">English</option> <option value="?&lang=fr">Français</option> <option value="?&lang=de">Deutsch</option> </select> JS: document.addEventListener('DOMContentLoaded', function() { const select = document.getElementById('select'); select.addEventListener('change', function() { if (this.value) { location.href = this.value; } }); // loop through select options // and if page URL contains option value, select it for (let i = 0; i < select.options.length; i++) { if (location.href.includes(select.options[i].value)) { select.value = select.options[i].value; break; } } }); Custom select solution: HTML: <div id="my-select"> <div id="my-select-label">Lëtzebuergesch</div> <div id="my-select-options"> <div data-value="?&lang=lu">Lëtzebuergesch</div> <div data-value="?&lang=en">English</div> <div data-value="?&lang=fr">Français</div> <div data-value="?&lang=de">Deutsch</div> </div> </div> CSS: #my-select { width: 150px; } #my-select:hover #my-select-options { display: block; } #my-select-options { display: none; } #my-select-options > div { padding: 0.5em; border: 1px solid black; border-top: none; } #my-select-label { margin-top: 2em; padding: 1em; border: 1px solid black; } JS: document.addEventListener('DOMContentLoaded', function() { const mySelectLabel = document.getElementById('my-select-label'); const mySelectOptions = document.querySelectorAll('#my-select-options > div'); for (let i = 0; i < mySelectOptions.length; i++) { mySelectOptions[i].addEventListener('click', function() { location.href = this.getAttribute('data-value'); }); } for (let i = 0; i < mySelectOptions.length; i++) { if (location.href.includes(mySelectOptions[i].getAttribute('data-value'))) { mySelectLabel.textContent = mySelectOptions[i].textContent; break; } mySelectLabel.textContent = mySelectOptions[0].textContent; } }); If you have any questions, ask.
Hide tab based on language selection
I'm trying to hide the other tab (the label and the tab itself) when a language is selected. I can't understand what I'm doing wrong, I tried to change different times the code but there is something I cant get. It also doesn't give me any error in the console. Can anybody point me to the right direction? $(document).ready(function () { showtabs(); jQuery('#language').on('change', showtabs()); function showtabs() { jQuery('.tab_header a').show(); jQuery('.tab_form_lang').show(); var valueSelected = jQuery("#language option:selected").val(); if (valueSelected != 0) { jQuery('.tab_header').find('a').hide(); jQuery('.tab_form_lang').hide(); jQuery('a[langid=' + valueSelected + ']').show(); jQuery('.tab_form_lang[langid=' + valueSelected + ']').show(); } } }) .tab_header a { float: left; width: auto; height: 50px; line-height: 50px; padding-left: 15px; padding-right: 15px; color: #FFF; font-size: 15px; margin-right: 2px; background-color: #788288; text-transform: uppercase; } .tab_form.displaynone { display: none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <select class="form-control" default="0" request="0" initvalue="0" id="language" name="lingua" onchange="resetStepSelect(this.id)"> <option selected="selected" value="0">ALL ( default )</option> <option value="1">Italian</option> <option value="2">English</option> </select> <div class="tab_header col-sm-offset-2 nopadding_right col-sm-10"> <a class="selected" langid="1" id="tab_lang_0" href="javascript:changeTab(0)" title="" data-original-title="Italian" style="display: block;">Italian</a> <a langid="2" id="tab_lang_1" href="javascript:changeTab(1)" title="" data-original-title="English" style="display: none;">English</a> </div> <div langid="1" class="tab_form tab_form_lang col-sm-12" id="tab_form_0" style="display: block;"> the content of the tab with langid=1 </div> <div langid="2" class="tab_form tab_form_lang col-sm-12 displaynone" id="tab_form_1" style="display: block;"> the content of the tab with langid=2 </div>
Change this line : jQuery('#language').on('change', showtabs()); to : jQuery('#language').on('change', showtabs); A recommendation try to use jQuery('a[langid="' + valueSelected + '"]')... instead jQuery('a[langid=' + valueSelected + ']')...
Values not getting saved onsubmit of form using local storage
I want to capture 2 values (product name and energy consumption)from a form and store it using local Storage. OnClick I want to display the stored values on the side of the form. What is working local storage is getting set. Issues (in the commented function compareSetup) 1) My guess is I am not getting the selected product nor the energy values from the form itself. 2) wrote the display logic but getting error on that line Uncaught SyntaxError: Unexpected identifier. I tried 2 different ways. I am newbie hence trying different syntax 3) Resources tab in Chrome shows callAnnual as undefined callProduct as 0 4) alerts inside function did not work I missing something. either logically or syntaxwise or both. Can some one guide me please. Thanks for your time. 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 configureDropDownLists(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'); //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} 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; } } function createOption(ddl, text, value) { var opt = document.createElement('option'); opt.value = value; opt.text = text; ddl.options.add(opt); } function configureProductDropDownLists(product) { document.getElementById('wattage').innerText = wattage[product.value]; } 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"; } 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"; } } /* function compareSetup(){ // I am trying to set the local storage for 2 things : selected [product name and Annual Energy Consumption]. End goal is to use them inorder to plot a chart //initialize the selected product and annual consumption by calling their latest values on submit var submittedProduct = document.getElementById("products").options.selectedIndex; var submittedAnnualEnergyConsumption = document.getElementById("annualEnergyConsumption").value; //alert(submittedProduct); //setting the local storage with a key and variable name which was defined above localStorage.setItem("callProduct", submittedProduct); localStorage.setItem("callAnnual", submittedAnnualEnergyConsumption); //get Item with a key and display var displayName = localStorage.getItem("callProduct"); //alert(callProduct); displayName = document.getElementById("displayName"); var displayAnnual = document.getElementById("displayAnnual").innerHTML = localStorage.getItem parseInt(("callAnnual")); // return false as I dont want the form to submit return false; } */ $(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(); }); }); /* annualCost = function() { // utility rate currently is hard coded but this will come from the database and shall be inputted by user once. Utility Rate does not change that often var utilityRate = 0.11; var button = document.getElementById('annualCost'); var annualCost = parseFloat( annualEnergy * utilityRate).toFixed(2); document.getElementById('annualCostOperation').innerText= "$" + annualCost ; } */ #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; } <h2>Annual Energy Consumption and Cost Calculator</h2> <form method="post" onSubmit="return compareSetup()"> <div id="leftColumn"> <div> <span class="placeholderText">Choose Category</span> <span> <select id="ddl" onchange="configureDropDownLists(this,document.getElementById('products'))"> <option value="">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="configureProductDropDownLists(this)"> <option selected>--------------------------</option> </select> </span> </div> <div> <span class="placeholderText">Wattage</span> <span id="wattage">---</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="AllYear" id="allYear" onclick="annualEnergyConsumption(365)" /> <label for="allYear">All year</label> <input type="radio" name="usageRadio" value="halfYear" id="halfYear" onclick="annualEnergyConsumption(182)" /> <label for="halfYear">6 Months</label> <input type="radio" name="usageRadio" value="threeMonths" id="threeMonths" onclick="annualEnergyConsumption(90)" /> <label for="threeMonths">3 Months</label> <input type="radio" name="usageRadio" value="oneMonth" 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" /> </div> <div id="right"> <div id="displayName">Selected Product 1</div> <div id="displayAnnual">Selected Product1's Annual Consumption</div> </div> <!-- <div id="right"> </form> <div> <span class="placeholderText">Enter your Utility Rate per Kw/h</span></br> <span><input type="number" id="utilityRate" /></span> </br></br> </div> <div> <span class="placeholderText"><button id="annualCost" onclick='annualCost()'>Annual Cost to Operate</button></span></br> <span id="annualCostOperation" /></span> </div> </div> --> </form>
Your scope access of '$' as undefined should be a dead give away as to why the remainder of the code is not working. Once you have called the '$' bit of code within the proper scope it will work.
The HTTP verb POST used to access path ' ' is not allowed on IIS 7
I am a Bit new on this ..I am Replicating this Demo Example on my Local Server http://www.bibeault.org/jqia2/chapter4/dvds/dvds.html In Live Example Resulting data gets properly loaded ..But Not on My Machine ..My Code and css are exactly same , Update : Recently Tracked error : >POST http://localhost:1701/applyFilters 405 Method Not Allowed<br/> The HTTP verb POST used to access path '/applyFilters' is not allowed. it is on .Net Server.... resulting data comes from this Page http://www.bibeault.org/jqia2/chapter4/dvds/applyFilters ... Do I need to completely recreate this page on My server also ?..Need some guidence My Code: <!DOCTYPE html> <html> <head> <title>DVD Ambassador — Disc Locator</title> <link rel="stylesheet" type="text/css" href="Styles/dvds.css"> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.js"></script> <script type="text/javascript"> var filterCount = 0; $(function () { $('#addFilterButton').click(function () { var filterItem = $('<div>') .addClass('filterItem') .appendTo('#filterPane') .data('suffix', '.' + (filterCount++)); $('div.template.filterChooser') .children().clone().appendTo(filterItem) .trigger('adjustName'); }); $('select.filterChooser').live('change', function () { var filterType = $(':selected', this).attr('data-filter-type'); var filterItem = $(this).closest('.filterItem'); $('.qualifier', filterItem).remove(); $('div.template.' + filterType) .children().clone().addClass('qualifier') .appendTo(filterItem) .trigger('adjustName'); $('option[value=""]', this).remove(); }); $('button.filterRemover').live('click', function () { $(this).closest('div.filterItem').remove(); }); $('.filterItem [name]').live('adjustName', function () { var suffix = $(this).closest('.filterItem').data('suffix'); if (/(\w)+\.(\d)+$/.test($(this).attr('name'))) return; $(this).attr('name', $(this).attr('name') + suffix); }); $('#addFilterButton').click(); $('#filtersForm').submit(function () { $('#resultsPane').load('applyFilters', $('#filtersForm').serializeArray()); return false; }); /* bonus exercise code -- uncomment to enable $('input.numeric').live('keypress',function(event){ if (event.which < 48 || event.which > 57) return false; }); */ }); </script> </head> <body> <div id="pageContent"> <h1>DVD Ambassador</h1> <h2>Disc Locator</h2> <form id="filtersForm" action="/fetchFilteredResults" method="post"> <fieldset id="filtersPane"> <legend>Filters</legend> <div id="filterPane"></div> <div class="buttonBar"> <button type="button" id="addFilterButton">Add Filter</button> <button type="submit" id="applyFilterButton">Apply Filters</button> </div> </fieldset> <div id="resultsPane"><span class="none">No results displayed</span></div> </form> </div> <!-- hidden templates --> <div id="templates"> <div class="template filterChooser"> <button type="button" class="filterRemover" title="Remove this filter">X</button> <select name="filter" class="filterChooser" title="Select a property to filter"> <option value="" data-filter-type="" selected="selected">-- choose a filter --</option> <option value="title" data-filter-type="stringMatch">DVD Title</option> <option value="category" data-filter-type="stringMatch">Category</option> <option value="binder" data-filter-type="numberRange">Binder</option> <option value="release" data-filter-type="dateRange">Release Date</option> <option value="viewed" data-filter-type="boolean">Viewed?</option> </select> </div> <div class="template stringMatch"> <select name="stringMatchType"> <option value="*">contains</option> <option value="^">starts with</option> <option value="$">ends with</option> <option value="=">is exactly</option> </select> <input type="text" name="term"/> </div> <div class="template numberRange"> <input type="text" name="numberRange1" class="numeric"/> <span>through</span> <input type="text" name="numberRange2" class="numeric"/> </div> <div class="template dateRange"> <input type="text" name="dateRange1" class="dateValue"/> <span>through</span> <input type="text" name="dateRange2" class="dateValue"/> </div> <div class="template boolean"> <input type="radio" name="booleanFilter" value="true" checked="checked"/> <span>Yes</span> <input type="radio" name="booleanFilter" value="false"/> <span>No</span> </div> </div> </body> </html> My Css: body { background-image: url(backg.jpg); } body,td,th { font-family: Verdana,sans-serif; font-size: 10pt; } #templates { display:none; } #pageContent { width: 720px; background-color: white; color: #444444; border: 2px ridge #888888; margin: 32px auto; padding: 8px 32px; } h1,h2 { text-align: center; } h1,h2,h3 { margin: 0; } fieldset,legend { border: 2px ridge silver; } fieldset { padding-top: 12px; } legend { padding: 3px 12px; background-color: silver; font-weight: bold; } #filterPane { margin-bottom: 16px; } .filterItem * { margin-right: 4px; margin-bottom: 4px; } #resultsPane { margin-top: 14px; } #resultsPane span.none{ color: silver; font-style: italic; } #resultsPane table { background-color: #444444; width: 100%; margin-top: 12px; } #resultsPane th { background-color: silver; border: 2px outset silver; font-size: 0.9em; } #resultsPane td { background-color: white; padding: 1px 12px; font-size: 0.8em; text-align: center; } #resultsPane td:first-child { text-align: left; } input.numeric { width: 48px; } input.dateValue { width: 64px; } Solved This was just needed to add in web.config for IIS7 <?xml version="1.0"?> <configuration> <system.webServer> <handlers> <add name="htm" path="*.htm" verb="*" modules="IsapiModule" scriptProcessor="%windir%\system32\inetsrv\asp.dll" resourceType="Either" /> </handlers> </system.webServer> </configuration> Everybody suggestion and this post helped: http://zhongchenzhou.wordpress.com/2011/12/05/iis-7-7-5-allow-post-requests-to-html-files/
Basically that demo is running on an Apache server, not under IIS. The dvd list at http://www.bibeault.org/jqia2/chapter4/dvds/applyFilters is only a file with no extension. if you browser one level above http://www.bibeault.org/jqia2/chapter4/dvds/ you can see the file list. The quick fix is to rename it to a applyFilters.html on your local version and change the load reference. The alternative is to allow files without extensions to be loaded under IIS (which is off by default for security reasons).
Assuming you are running some kind of development server: The server does not allow POST requests. Try to deploy your code on a real server and it should work. Someone had similar problems and it was the VisualStudio Development server which caused the problem (http://www.mojoportal.com/Forums/Thread.aspx?pageid=5&t=6383~-1). At the moment applyFilters is accessed on your local server. You could try: $('#resultsPane').load('http://url.to.other.server/applyFilters', $('#filtersForm').serializeArray()); But then you have cross-site scripting. You should use a local version of applyFilters (and allow POST requests). It seems like IIS does not allow POST requests on HTML files: https://serverfault.com/a/349193/133535