Values not getting saved onsubmit of form using local storage - javascript

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.

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"];

Having trouble using local storage for css toggle switch

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();
}
});

trying to get the value of a random number and put it in a specific div

I'm trying to display random number in a specific div or grid do i need to store number first i would like some advice on how i can achieve this. for example if random number is 4 i would like that value in div 4, then if my next random number is 10 place it in div 10
browser example
function lottoNumbers() {
var lottoNums = [];
for (var i = 0; i < 1; i++) {
var temp = Math.floor(Math.random() * 12);
if (lottoNums.indexOf(temp) == -1) {
`enter code here`
lottoNums.push(temp);
document.getElementById('square' + i).innerHTML = lottoNums[i];
} else {
i--;
}
}
}
<body bgcolor="lightblue">
<h1>
<center>GENERATE LOTTO NUMBERS</center>
</h1>
<div class="divContainer">
<div id=square0 class=num></div>
</div>
</br>
<div class="hej">
<div id=square1 class=nums></div>
<div id=square2 class=nums></div>
<div id=square3 class=nums></div>
<div id=square4 class=nums></div>
</div>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
<div class=hei>
<div id=square5 class=nums></div>
<div id=square6 class=nums></div>
<div id=square7 class=nums></div>
<div id=square8 class=nums></div>
</div>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
<div class="hek">
<div id=square9 class=nums></div>
<div id=square10 class=nums></div>
<div id=square11 class=nums></div>
<div id=square12 class=nums></div>
</div>
<center>
<input id="btn" class="knapp" type="button" value="lotto" onClick="lottoNumbers();">
</cennter>
</body>
</html>
Your number wasn't being placed on the right spot as You generated the temp variable which is the random number, but have addressed it to variable i which is the iterator of the for loop. This way, if You would generate 3 random numbers, they would be placed in the divs square0, square1, square2 when they actually should be placed in the divs 'square'+temp that correspond to the actual generated number. Please see my example:
document.getElementById ("btn").addEventListener ("click", lottoNumbers, false);
function lottoNumbers() {
var lottoNums = [];
for (var i = 0; i < 1; i++) {
var temp = Math.floor(Math.random() * 12) + 1;
lottoNums.push(temp);
document.getElementById('square' + temp).innerHTML = lottoNums[i];
document.getElementById('square0').innerHTML = lottoNums[i];
}
}
.num {
border: 1px solid;
width: 20px;
height: 20px;
margin: 2px;
}
.nums {
border: 1px solid;
width: 20px;
height: 20px;
margin: 2px;
float: left;
}
body {
background-color: lightblue;
}
.hej{
float: left;
width: 120px;
height: 30px;
clear: both;
}
.hei{
float: left;
width: 120px;
height: 30px;
clear: both;
}
.hek{
float: left;
width: 120px;
height: 30px;
clear: both;
}
.divContainer{
float: right;
width: 20px;
height: 20px;
font-size: 15px;
}
<h1>
<center>GENERATE LOTTO NUMBERS</center>
</h1>
<div class="divContainer">
<div id="square0" class="num"></div>
</div>
<div class="hej">
<div id="square1" class="nums"></div>
<div id="square2" class="nums"></div>
<div id="square3" class="nums"></div>
<div id="square4" class="nums"></div>
</div>
<div class="hei">
<div id="square5" class="nums"></div>
<div id="square6" class="nums"></div>
<div id="square7" class="nums"></div>
<div id="square8" class="nums"></div>
</div>
<div class="hek">
<div id="square9" class="nums"></div>
<div id="square10" class="nums"></div>
<div id="square11" class="nums"></div>
<div id="square12" class="nums"></div>
</div>
<input id="btn" class="knapp" type="button" value="lotto"">
You can just change
document.getElementById('square' + i).innerHTML = lottoNums[i];
to
document.getElementById('square' + lottoNums[i]).innerHTML = lottoNums[i];
to put each random number in the div matching that number.

Form to fill excel spreadsheet

I've been trying to build an application to submit form selections to an existing spreadsheet on a local machine. This is intended for a windows machine, but I am working on ubuntu, and don't have access to a windows development environment. With this, I'm trying to parse an excel document, find the bottom row, capture the 'ingredients' list, or other form values, then insert the value of the hash into the excel column and save the changes to the document. Any suggestions on where I should start would be great.
-- Thanks a million
//Script
$(document).ready(doInput);
function doInput(){
var ingreds = $('.ingredients');
var count = $('.count');
var runs = $('#runs');
var cb = $('.cb');
var bb = $('.bb');
var fullDate = new Date();
var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);
var currentDate = twoDigitMonth + "/" + fullDate.getDate() + "/" + fullDate.getFullYear();
var bbDate = fullDate.getMonth() + 8;
cb.html("C&B:<br />" + currentDate);
if (bbDate > 12){
bb.html("BB:<br />" + "0" + (bbDate - 12) + "/" + fullDate.getDate() + "/" + (fullDate.getFullYear() + 1));
}else{
bb.html("Best By:<br />" + bbDate + "/" + fullDate.getDate() + "/" + fullDate.getFullYear());
}
var recipes = {
'Volvo': {
'Torq': 1231,
'Leather': 131,
'Blue': 22
},
'Jet': {
'HP': 1233,
'Leather': 121,
'Candy': 1313,
'Gas': 1313,
'Billiard': 223
},
'Mac': {
'Torq': 12111,
'Cheddar': 123
},
'Hog': {
'Torq': 475,
'Sugar': 12,
'Sheer': 11,
'Water': 2323,
'Wheels': 3
}
}
var recipe;
ingreds.html("Ingredients:<br />");
count.html("The Yield is:" + $('#yield').val() + "?<br />");
if ($("option:selected").val() == 'volv') {
recipe = recipes['Volvo'];
}else if($("option:selected").val() == 'jet') {
recipe = recipes['Jet'];
}else if($("option:selected").val() == 'mac') {
recipe = recipes['Mac'];
}else if($("option:selected").val() == 'hog') {
recipe = recipes['Hog'];
}
for (key in recipe){
if(key == 'Sugar'){
ingreds.append(key + ": " + recipe[key] * runs.val() + 'Lbs<br />');
}else{
ingreds.append(key + ": " + recipe[key] * runs.val() + 'g<br />');
}
}
return true;
}
body {
background: rgba(150,150,150,.5);
}
.container {
width: 80%;
margin: auto;
padding: 10px;
}
.ingredients {
padding: 10px;
padding-left: 20px;
}
.count {
margin-top: 25px;
font-weight: Bold;
color: #700;
}
.submit,
.ingredients,
.flavor,
.runs,
.yieldShell,
.bestBy,
.cb,
.bb {
min-width: 215px;
}
.count {
min-width: 190px;
}
.row {
margin-right: -15px;
margin-left: -15px;
}
.row:before,
.row:after {
display: table;
content: " ";
}
.row:after {
clear: both;
}
.col-sm-4{
position: relative;
min-height: 1px;
padding-right: 15px;
padding-left: 15px;
}
#media (min-width: 540px) {
.container {
width: 750px;
}
.col-sm-4 {
float: left;
width: 33.33333333333333%;
}
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<div class="container">
<form oninput="doInput()">
<div class="row">
<div class="flavor col-sm-4">
Flavor:<br />
<select name="flavors">
<option value="volv" selected="selected">Volvo</option>
<option value="jet">Jet</option>
<option value="mac">Mac</option>
<option value="hog">Hog</option>
</select>
</div>
<div class="runs col-sm-4">
Number of runs:<br />
<input type="number" id="runs" name="runs" value="1">
</div>
</div>
<div class="row">
<div class="ingredients col-sm-4"></div>
<div class="yieldShell col-sm-4">
<div class="yield">Yield:<br />
<input type="number" id="yield" name="yield" value="450">
</div>
<div class="count col-sm-4"></div>
</div>
</div>
<div class="row">
<div class="submit col-sm-4">
<input type="submit" value="Save to Production Log?">
</div>
<div class="bestBy col-sm-4">
<div class="row">
<div class="col-sm-4 cb"></div>
</div>
<div class="row">
<div class="col-sm-4 bb"></div>
</div>
</div>
</div>
</form>
</div>
Are you not looking at this from the wrong angle?
Rarely would you try to access an Excel document directly, since the quantity of 'irrelevant' data is huge (data needed by Excel to reconstruct the page itself, but not directly related to the data the user is storing - meta-data if you will; i.e. font used, size of font, etc.).
Usually you would output the data to a CSV and allow the user to import the data into any spreadsheet program, which gives you greater flexibility and is simpler to code.
In terms of adding the data, you could easily open the existing CSV and append new data, or search the file and insert the data where required. However, if others are to use the CSV then I'd save the data in a single-table database as well as in the CSV. Then you simply construct a new CSV each time, overwriting any existing file if necessary.
No code help here at present, and I might be wrong, but this is the approach I have used and seen used.

How do I make my iframe responsive for all devices?

I am not an expert in HTML, CSS, or JavaScript, but I have this website that needs to be responsive on all devices. However, it does not seem like it is working for some reason and instead creates major gaps of white space when I view the website on a mobile web browser:
Here is the code for it:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">
<title>untitled document</title>
<style media="screen">
body {
background-color: #f0f0f0;
font: 1em verdana, arial, helvetica, sans-serif;
line-height: 0px;
}
h1,h2 {
font-size: 2em;
color: #f00;
text-align: center;
text-shadow: 0 0 0.06em #000,0 0 0.12em #000;
}
.af-textWrap {
display: block;
text-align: center;
color: #b7b7b7;
}
.af-element {
text-align: center;
}
#awf_field-90534028,
#awf_field-90534029 {
display: block;
width: 98%;
max-width: 28.125em;
margin: auto;
text-align: left;
}
.image {
display: block;
width: 98%;
max-width: 30em;
height: auto;
margin: auto;
}
</style>
</head>
<body>
<div id="worked"></div>
<script src="https://fast.wistia.com/embed/medias/cj7247tp29.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_cj7247tp29 videoFoam=true" style="height:100%;width:100%"> </div></div></div>
<h1>Offer Ends In:</h1>
<h2 id="time"></h2>
<!-- AWeber Web Form Generator 3.0.1 -->
<form class="af-form-wrapper" accept-charset="UTF-8" action="https://www.aweber.com/scripts/addlead.pl" method="post">
<input name="meta_web_form_id" type="hidden" value="604218668">
<input name="meta_split_id" type="hidden" value="">
<input name="listname" type="hidden" value="awlist4661276">
<input id="redirect_56ab2ff33416d920a3c24dc4d8e140f4" name="redirect" type="hidden" value="http://bloggingnetworkonline.com/InternetMarketing/?page_id=133&preview=true">
<input name="meta_adtracking" type="hidden" value="My_Web_Form">
<input name="meta_message" type="hidden" value="1">
<input name="meta_required" type="hidden" value="name,email">
<input name="meta_tooltip" type="hidden" value="name||First Name...,,email||Best Email...">
<div id="af-form-604218668" class="af-form">
<div id="af-body-604218668" class="af-body af-standards">
<div class="af-element">
<label class="previewLabel" for="awf_field-90534028"></label>
<div class="af-textWrap">
<input id="awf_field-90534028" class="text" tabindex="500" name="name" type="text" placeholder="First Name...">
</div>
</div>
<div class="af-element">
<label class="previewLabel" for="awf_field-90534029"></label>
<div class="af-textWrap">
<input id="awf_field-90534029" class="text" tabindex="500" name="email" type="text" placeholder="Best Email...">
</div>
</div>
<div class="af-element buttonContainer">
<input id="af-submit-image-604218668" class="image" tabindex="502" alt="Submit Form" name="submit" src="https://hostedimages-cdn.aweber-static.com/MTE0ODQyNQ==/original/d316599087b84f9498e3854009bdad52.png" type="image"/>
</div>
<div class="af-element privacyPolicy">
<p><strong>I respect your <a title="Privacy Policy" href="https://www.aweber.com/permission.htm" target="_blank" rel="nofollow">email privacy</a></strong></p>
<div class="af-clear"> </div>
</div>
</div>
</div>
<div style="display: none;"><img src="https://forms.aweber.com/form/displays.htm?id=bAwsTIwcbGwc" alt="">
</div>
</form>
<!-- /AWeber Web Form Generator 3.0.1 -->
<script>
(function() {
'use strict';
var handler = function() {
if (--sec < 0) {
sec = 59;
if (--min < 0) {
min = 0;
sec = 0;
}
}
var min1 = '0' + min + 'm';
var min2 = min + 'm';
var sec1 = '0' + sec + 's';
var sec2 = sec + 's';
var col = ':';
document.getElementById('time').textContent = (min < 10 ? min1 : min2) + col + (sec < 10 ? sec1 : sec2);
};
var sec = 0;
var min = 15;
handler();
setInterval(handler, 1000);
}());
</script>
</body>
</html>
Looks like your iframe is injected by JavaScript so I personally suggest adding a setInterval() to your code to monitor the iframe element. Once the iframe element is available, get the body in the iframe and set it's margin to 0.
$(function() {
$('#test').append('<iframe src="http://www.w3schools.com"></iframe>');
var timer = setInterval(function() {
$('iframe').load( function() {
$('iframe').contents().find("head").append($("<style type='text/css'>body{margin:0;}</style>"));
clearInterval( timer ); // Clear the interval
});
}, 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>

Categories