same background color for all pages - javascript

I want to make the customer choose a color and then when he go to other page, the color stay the same. this is the code for the choosing color on the first page:
<select id="color" style="width: 5%; height: 10%" size="5">
<option value="white">White</option>
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
<script>
document.getElementById("color").onchange = function () {
document.body.style.background = this.options[this.selectedIndex].value;
}

This seems like a good use case for localStorage:
document.querySelector('#color').addEventListener('change', function () {
document.body.style.background = this.value;
localStorage.setItem('appColor', this.value);
});
document.body.style.background= localStorage.getItem('appColor');
See this Fiddle. Each time you choose a color, it's remembered and will be the default color the next time you run it.
Side note: You can simplify this:
this.options[this.selectedIndex].value;
… to this:
this.value;

This should be your script:
<body onload="OnLoad()"> //onLoad: run the function OnLoad() when the body is being load
<select id="color" style="width: 5%; height: 10%" size="5">
<option value="white">White</option>
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
<script>
function OnLoad() {
document.getElementById("color").onchange = function () { //Getting the background color from the select
document.body.style.background = this.options[this.selectedIndex].value; //Setting the background color
document.cookie="WebBackgroundColor=" + this.options[this.selectedIndex].value; //Storing in a cookie named: WebBackgroundColor the color that was chosen
}
var color = getCookie("WebBackgroundColor"); //Getting the color stored on the cookie
document.body.style.background = color; //Setting the background color to the same color as stored in the cookie
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
</script>
</body>
To add this script to other pages you need to change the body from: <body> to <body onload="OnLoad()">
and you need to add all the script thing at the bottom of the page (or the header part):
<script>
function OnLoad() {
document.getElementById("color").onchange = function () { //Getting the background color from the select
document.body.style.background = this.options[this.selectedIndex].value; //Setting the background color
document.cookie="WebBackgroundColor=" + this.options[this.selectedIndex].value; //Storing in a cookie named: WebBackgroundColor the color that was chosen
}
var color = getCookie("WebBackgroundColor"); //Getting the color stored on the cookie
document.body.style.background = color; //Setting the background color to the same color as stored in the cookie
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
</script>

Related

Default value not working in select tag if the user doesn't select any options?

Hello,
I'm trying to make a default value of language selection to be English whose value is 1. So if the user doesn't select language option, it should still be 1 so that I can run my algorithm. But when I test it that doesn't select any value, it doesn't make it default value.
And I decided to check the datatype of language option, it's a string type, but even if I make if(isNaN(languageOption)){ languageOption = "1";}, it's still not working. Can anyone tell me why?
Thank you for your help
<body>
<div>
<img src="image/MindScribe-cursive.png" id="cursive">
</div>
<div id="container">
<img src="image/MindScribe-zebra.png" id="ImageEnterVariables" alt="Hello, I'm Stripes">
<img src="image/MindScribe-zebra2.png" id="onlyShowZebraImage" alt="Hello, I'm Stripes" style=display:none>
<select id="languageSelection" style=display:none>
<option value="">Choose a language</option>
<option value="1">English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
<script>
var languageOption = parseInt($("#languageSelection").val() );
$("#languageSelection").on("change", function(){
if(isNaN(languageOption)){ languageOption = "1";}
languageOption = $(this).val();
console.log("langugeOption is " + languageOption);
console.log("Language changed to: "+ $(this).find("option").eq( $(this)[0].selectedIndex ).text() + " (Index: "+languageOption+")" );
console.log(typeof(languageOption)); // Outputs string
endingArr = [];
runThroughArr = [];
randomArr = [];
if(languageOption === "1"){
console.log("English");
for(i = 0; i < intro_playList.length; i++){
if(intro_playList[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList[i].runThrough){ runThroughArr.push(i); }
if(intro_playList[i].random){ randomArr.push(i); }
}
}
else if (languageOption === "2"){
console.log("Chinese");
for(i = 0; i < intro_playList_chi.length; i++){
if(intro_playList_chi[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList_chi[i].runThrough){ runThroughArr.push(i); }
if(intro_playList_chi[i].random){ randomArr.push(i); }
}
}
});
</script>
</body>
Why you are doing these much stuff for making English default value? You can just add selected attribute to that option which you want to make default.
<select id="languageSelection" style=display:none>
<option value="">Choose a language</option>
<option value="1" selected>English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
And in your script, you can apply below logic to set default option to 1 :
languageOption = $(this).val();
if(languageOption==""){
languageOption="1";
}
$("#languageSelection").on("change", function(){
var languageOption = $(this).val();
if(languageOption.length==0){
languageOption=1;
}
console.log("langugeOption is " + languageOption);
console.log("Language changed to: "+ $(this).find("option").eq( $(this)[0].selectedIndex ).text() + " (Index: "+languageOption+")" );
console.log(typeof(languageOption)); // Outputs string
endingArr = [];
runThroughArr = [];
randomArr = [];
if(languageOption === "1"){
console.log("English");
for(i = 0; i < intro_playList.length; i++){
if(intro_playList[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList[i].runThrough){ runThroughArr.push(i); }
if(intro_playList[i].random){ randomArr.push(i); }
}
}
else if (languageOption === "2"){
console.log("Chinese");
for(i = 0; i < intro_playList_chi.length; i++){
if(intro_playList_chi[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList_chi[i].runThrough){ runThroughArr.push(i); }
if(intro_playList_chi[i].random){ randomArr.push(i); }
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="languageSelection" >
<option value="">Choose a language</option>
<option value="1">English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
Above code works for me, it gives me 1 if Choose a language is selected.
If you need the "Choose a language" to be displayed, set its value to 1 (the same as English):
<option value="1">Choose a language</option>

How to hide select option with condition Less than (<)

There are two select lists call #ageSelect1 and #ageSelect2. I want to hide #ageSelect2 options when page load less than some value. Following code is not working. But
$("#ageSelect2 option[value =" + ageSelectStart + "]").hide();
code is working. how to use less than condition.?
<script type = "text/javascript" >
$(document).ready(function() {
var ageSelectStart = 21;
var ageSelectEnd = 35;
$("#ageSelect2 option[value <" + ageSelectStart + "]").hide();
});
< /script>
try this
$(window).load(function() {
var ageSelectStart = 21;
var ageSelectEnd = 35;
var elSelect1 = $("#ageSelect1"),
elSelect2 = $("#ageSelect2");
elSelect1.find('option').each(function(index, el){
if($(el).val() < ageSelectStart){
//$(el).prop('disabled', true).hide();
$(el).remove();
}
});
elSelect2.find('option').each(function(index, el){
if($(el).val() > ageSelectEnd){
//$(el).prop('disabled', true).hide();
$(el).remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select name="startage" id="ageSelect1">
<option value="10">10</option>
<option value="11">11</option>
<option value="21">21</option>
<option value="22">22</option>
</select>
<select name="endage" id="ageSelect2">
<option value="36">36</option>
<option value="37">37</option>
<option value="24">24</option>
<option value="25">25</option>
</select>
<script type = "text/javascript" >
$(document).ready(function() {
var ageSelectStart = 21;
var ageSelectEnd = 35;
$("#ageSelect2").find("option").show().each(function() {
if ($(this).attr("value") < ageSelectStart) {
$(this).hide();
}
});
});
</script>
Just try this
<script type = "text/javascript" >
$(document).ready(function() {
var ageSelectStart = 21;
var ageSelectEnd = 35;
var selectedElement =document.getElementById("ageSelect2")
for (var i=0; i<selectedElement.length; i++)
{
if (selectedElement.options[i].value < ageSelectStart)
{
selectedElement.options[i].hide();
}
}
});
< /script>

Count Unique Selection from Multiple Dropdown

I'm new to jquery, I'm working on a survey form and I have multiple dropdown menus for different questions but they all have the same dropdown value. Supposed I have:
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
And other different dropdowns with different id's. What is the best way to count how many has selected Yes, No and N/A/ ? Thanks
you can do it simple this way
$('select').change(function() {
// get all selects
var allSelects = $('select');
// set values count by type
var yes = 0;
var no = 0;
// for each select increase count
$.each(allSelects, function(i, s) {
// increase count
if($(s).val() == 'Yes') { yes++; }
if($(s).val() == 'No') { no++; }
});
// update count values summary
$('.cnt-yes').text(yes);
$('.cnt-no').text(no);
});
DEMO
Try this — https://jsfiddle.net/sergdenisov/h8sLxw6y/2/:
var count = {};
count.empty = $('select option:selected[value=""]').length;
count.yes = $('select option:selected[value="Yes"]').length;
count.no = $('select option:selected[value="No"]').length;
count.nA = $('select option:selected[value="N/A"]').length;
console.log(count);
My way to do it would be :
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
Check the console (or replace with alert).
With your code, it would be something like that (assuming you want to check on a button click event) :
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<button class="btn btn-primary" id="countYes"></button>
<script type="text/javascript">
$('#countYes').on('click', function(){
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
});
</script>
You can check at another event, I choosed a button click just for example.
There is likely a cleaner way to do this, but this will get the job done (assuming there is a button click to trigger things):
$("#theButton").on('click', function() {
var totalSelect = 0;
var totalYes = 0;
var totalNo = 0;
var totalNA = 0;
$("select").each(function(){
totalSelect++;
if ($(this).val() == "Yes") { totalYes++; }
if ($(this).val() == "No") { totalNo++; }
if ($(this).val() == "N/A") { totalNA++; }
});
});
Hope this helps the cause.
In common you can use change event:
var results = {};
$('select').on('change', function() {
var val = $(this).val();
results[val] = (results[val] || 0) + 1;
});
DEMO
If you want count for each type of select:
$('select').on('change', function() {
var val = $(this).val();
var name = $(this).attr('name');
if (!results[name]) {
results[name] = {};
}
results[name][val] = (results[name][val] || 0) + 1;
});
DEMO
In the results will be something like this:
{
"Forms[AgentIsPitch]": {
"Yes": 1,
"No": 2,
"N/A": 3
},
"Forms[MandatoryOptIsStated]": {
"No": 5,
"N/A": 13
},
}
UPD: for counting current choice:
$('select').on('change', function() {
var results = {};
$('select').each(function() {
var val = $(this).val();
if (val) {
results[val] = (results[val] || 0) + 1;
}
})
console.log(results);
});
DEMO

Choose city and redirect to url

The url redirection is not working. I need to let users to select a city and go to the url page. What am I doing wrong?
window.location.href = 'http://' + city + '.example.com';
Thank you.
<script type="text/javascript" src="/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
//<![CDATA[
$(function(){
var cityChosen = getCookie('citychosen');
if(cityChosen!=null && cityChosen!=''){
var chosen = $('#choose option[value="'+cityChosen+'"]');
chosen.attr('selected',true);
}
$("#choose").change(function(){
var selected = $("#choose option:selected");
var output = "";
window.location.href = 'http://' + city + '.example.com';
if(selected.val() != 0){
setCookie('citychosen',selected.val(),365);
}
$("#output").removeClass().addClass(selected.val()).html(output);
});
});
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function dropCookie(name) {
createCookie(name,"",-1);
}
//]]>
</script>
</head>
<body>
<select id="choose">
<option value="0">Select city</option>
<option value="amsterdam">Amsterdam</option>
<option value="newyork">New York</option>
<option value="london">London</option>
<option value="cardiff">Cardiff</option>
</select>
You seewindow.location.href here in this code is only a property that deals with the Url location. You need to set it to something in order to function.
The window.location.href is as same as var x="something" here.
So use the method window.open() which serves your purpose
window.open(window.location.href);
Note: There might be any mistake in spellings or syntax. i have just explained functionality. You can use varied parameters also. Have a look at this
First try to move window.location.href to the bottom of the $("#choose").change(function() {}); listener. Second, you are referencing a non-existent city variable, rename that to cityChosen.

Save dropped down value to cookies

I have a dropped down button and when chosen will be save to cookie.
I have to save in cookie so that I can redeem in the checkout page.
Have this so far but cant save them to the cookies:
function storeValues(form)
{
setCookie("product1",form.product1.value);
return true;
}
</script>
<ul>
<li><img src="images/1.jpg" alt="Product1" />
100% Pure Glutamine Powder</br>
Ultimate Recovery Fuel!*</br>
Supports Recovery From Workouts!*</br>
<form name="myform" action="checkout.html" method="POST">
<div align="center">
$12.99</br>
Select Quantity
<select name="product1" onchange="return storeValues(this);">>
<option value="1">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
</li>
There is no setCookie function in js. You can either use the jQuery cookie library or create your own set cookie function.
Use something like this (taken from http://www.quirksmode.org/js/cookies.html)
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}

Categories

Resources