Select option remain selected after submit/refresh - javascript

I'm working on a registration and I have fields for country and state.
My problem is the country and the state that I choose didn't retain after the submission.
I tried this
<script type="text/javascript">
document.getElementById('country').value = "<?php echo $_POST['country'];?>";
</script>
but didn't work.
so I tried another option using sessionStorage
$(function() {
$('#country').change(function() {
sessionStorage.setItem('todoData', this.value);
});
if(sessionStorage.getItem('todoData')){
$('#country').val(sessionStorage.getItem('todoData'));
}
});
</script>
It work on the country but not in the state, the choices is still the default options.
How can I fix that.. or is there another option to to make it work.
thanks.
SAMPLE CODE
JSFIDDLE

Here is a working example of the functionality you desire. I'm using localStorage like the person who answered before me.
https://jsfiddle.net/a0uj5d86/2/
//handle select changes, put new data in storage
document.getElementById('country').onchange = function () {
console.log('country change');
localStorage.setItem('country', this.value);
populateStates('country', 'state');
};
document.getElementById('state').onchange = function () {
localStorage.setItem('state', this.value);
};
document.getElementById('country2').onchange = function () {
localStorage.setItem('country2', this.value);
};
Then in populate countries at the end I have a little diddy that goes
var selection = 'USA';
if (localStorage.getItem(countryElementId)) {
console.log('found ' + countryElementId + ' in storage = ' + localStorage.getItem(countryElementId));
var selection = localStorage.getItem(countryElementId);
}
//select our country (default USA, or local storage if applicable)
findAndSelect(countryElementId, selection);
if (countryElementId == 'country') {
//we just populated country, now populate states
populateStates(countryElementId, stateElementId);
if (localStorage.getItem(stateElementId)) {
//if weve got a state to select, select it
findAndSelect(stateElementId, localStorage.getItem(stateElementId));
} else {
findAndSelect(stateElementId, 'Alabama');
}
}
I also did some odds-n-ends refactoring to the code you had. Give it a look and get back to me with any questions!

are you allowed to use HTML5 local storage?
var selectedVal = localStorage.getItem('selectedVal');
if (selectedVal){
$('#mySelect').val(selectedVal)
}
here is a fiddle
http://jsfiddle.net/jvso1Lcc/22/

Related

How to check/uncheck checkbox based on localStorage state

I'm trying to persist checkbox state in a HTML (Flask/Jinja2) template using just html and CSS, but I've running into strange behavior where even though localStorage saves the state correctly, state is always set as true on load. I've looked up a ton of answers and have been stuck for a couple hours and I don't understand it isn't working:
HTML:
<input id="returnHeatmapsHtmlCheckbox"
type="checkbox" name="returnHeatmapsHtml" onclick="saveCheckboxState(this)" />
JS:
<script type="text/javascript">
window.onload = onPageLoad();
function onPageLoad (){
document.getElementById("returnHeatmapsHtmlCheckbox").checked = localStorage.getItem("returnHeatmapsHtmlCheckbox");
}
// <!-- Persist checkboxes -->
function saveCheckboxState(e){
var id = e.id
var val = e.checked
console.log("Saved value ID: " + id + ","+ val)
localStorage.setItem(id,val)
console.log("Loaded value ID: " + localStorage.getItem(id,val))
console.log(getSavedCheckboxState("returnHeatmapsHtmlCheckbox"))
}
function getSavedCheckboxState(v){
const default_dict = {
"returnHeatmapsHtmlCheckbox": false
};
if (!localStorage.getItem(v)) {
return default_dict[v];// return false by default.
};
return localStorage.getItem(v);
}
</script>
Any help would be greatly appreciated, thank you !
I reviewed your code and took the liberty to refactor some excerpts, I tried to keep it as similar as possible to what you did, you can see the result below.
HTML:
<input id="myCheckbox" type="checkbox" name="myCheckbox" />
JS:
// get the checkbox element
const myCheckbox = document.querySelector('#myCheckbox')
// responsible for setting a value in localStorage
// following the "checked" state
const setStorageState = (e) => {
const { id, checked } = e.target
localStorage.setItem(id, checked)
}
// responsible for searching and converting to Boolean
// the value set in localStorage
const getStorageState = (storageName) => {
return localStorage.getItem(storageName) === 'true'
}
// responsible for changing the state of your checkbox
const setCheckboxStateOnLoad = () => {
myCheckbox.checked = getStorageState('myCheckbox')
}
// calls the function "setStorageState" every time
// the user clicks on his checkbox
myCheckbox.addEventListener('click', setStorageState)
// calls the "setCheckboxStateOnLoad" function
// after the DOM content is loaded
document.addEventListener('DOMContentLoaded', setCheckboxStateOnLoad)
Hope it helps and sorry for the bad english :)

How to short this type of js code

I want to minimize the code below and while maintaining the functionality.
please suggest me pattern which I can use for this kind of problems.
// tb bid pickup location picker.
$('#--tb-bid-pickup-location').on('keyup', function () {
toggler.toggler('#--tb-bid-location-picker', 'pulse');
});
// tb bid drop location picker.
$('#--tb-bid-destination-location').on('keyup', function () {
toggler.toggler('#--tb-bid-location-picker', 'pulse');
});
// tb bid drop location picker.
$('#--tb-bid-vehicle-type').on('keyup', function () {
toggler.toggler('#--tb-bid-truck-picker', 'pulse');
});
What about to create an "equilalency object" ?
A 2 columns sheet of strings to refer from clicked to affected.
var equiv = {
"--tb-bid-pickup-location" : "--tb-bid-location-picker",
"--tb-bid-destination-location" : "--tb-bid-location-picker",
"--tb-bid-vehicle-type" : "--tb-bid-truck-picker"
};
$( "[id^='--tb-bid']" ).on('keyup', function () {
// Get the clicked ID.
var thisID = $(this).attr("id");
// If that id exist in the equiv object.
if( equiv.hasOwnProperty(thisID) ){
toggler.toggler("#"+equiv[thisID], 'pulse');
}
});

How to display certain photos based on dropdown menu in mobile?

In my job, (I'm just a student worker, nothing major), my boss wants me to figure out a way to display photos on our website. Here's the catch:
My questions are:
is there a better way to go about this? Am I complicating things?
(I considered using a backend database to store the URLs so it would be easy to add/remove from the dropdown menu options, but that's proved to be difficult to figure out)
if this is a good way, how do I make it work on mobile?
$(function() {
// WHEN THE BUILDING CHANGES
$('#buildings').on('change', function() {
// set val equal to BUILDING VALUE
var val = $(this).val();
// set room = ROOMS
var room = $('#room');
// if it's the BSB, show the wings - else hide them.
if (val == "BSB") {
$('#wings').show();
// Change the room numbers based on selected Wing
$('#wings').on('change', function() {
val = $(this).val();
room.find('option').not(':first').hide();
$('option', room).filter(function() {
if ($(this).attr('data-group') == val) {
$(this).show();
}
});
room.val(0);
});
$('#wings').trigger('change');
// must not be the BSB
} else {
$('#wings').hide();
// select room based on Building
room.find('option').not(':first').hide();
$('option', room).filter(function() {
if ($(this).attr('data-group') == val) {
$(this).show();
}
});
room.val(0);
}
});
$('#buildings').trigger('change');
});
function setImage(select){
var image = document.getElementsByName("image-swap")[0];
image.src = select.options[select.selectedIndex].value;
}
function resetImage(){
var image = document.getElementsByName("image-swap")[0];
image.src = "";
}
CLICK HERE FOR THE JSFIDDLE OF MY CODE

How to remove null from my Javascript

So, here's my script:
$(function () {
// define this here because we're changing the ID
var $twitter = $('twitter');
// bind to select inside iframe
$('#iframe').on('load', function () {
$(this).contents().find('#cds').change(function () {
var selectVal = $(this).val();
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$twitter.attr("id", url);
}).change(); // trigger change to get initial value
});
});
Basically, it takes the selected value from my select box, and outputs it into a twitter link. The problem is, when nothing is selected, it outputs "null", and I was wondering if there was a way to detect this, and echo something else.
Try this:
var selectVal = $(this).val() || 'default value';

jquery cookie script only remembers checkboxes and not radio buttons

I have a js script that helps me create a cookie. It saves the checked checkboxes so this value is remembered (set in the cookie). Now the problem is that it doesn't seem to work with radio buttons. When reading the js-file, I see that input type=checkboxes. So it's logical it ignores radio buttons.
How do I change this script, so it will not only check the checked checkboxes, but also the checked radio buttons?
Many thanks
My js file script:
jQuery(document).ready(function(){
new chkRemembrance();
});
function chkRemembrance(){
this.__construct();
}
chkRemembrance.prototype = {
__construct : function(){
this.chk = this.fetchData(); // initialise array to store the checkboxes
this.init();
},
init : function(){
// first initialise all checkboxes that are checked
for(c in this.chk){
$("input[type=checkbox]#" + c).attr('checked', this.chk[c]);
}
// now make sure we fetch the checkbox events
var o = this;
$("input[type=checkbox]").change(function(){
o.saveData(this.id, this.checked);
})
},
fetchData : function(){
var r = {};
if ($.cookie('chk')){
r = JSON.parse($.cookie('chk'));
}
return r;
},
saveData : function(id,status){
this.chk[id] = status;
$.cookie('chk', JSON.stringify(this.chk));
}
}
It looks like you should just be able to add in the radio buttons and it will work.
Change this:
$("input[type=checkbox]#" + c).attr('checked', this.chk[c]);
To this:
$("input[type=checkbox]#" + c + ", input[type=radio]#" + c).attr('checked', this.chk[c]);
And change this:
$("input[type=checkbox]").change(function(){...});
To this:
$("input[type=checkbox], input[type=radio]").change(function(){...});

Categories