jquery cookie script only remembers checkboxes and not radio buttons - javascript

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

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 :)

Get dynamic state radiobutton in function

I am learning js, and I have a question that has confused me a little, I made a wrapper for the radiobutton, it is displayed in a modal window, and I want to transfer the value of the variable radiobutton to another function, tried it through var radioValue = $("input[name='radio']:checked").val();, but it retains the value that was when the page was loaded
$('input:radio[name=radio]').on('change', function () {
radioValue = $("input[name='radio']:checked").val();
});
(function(w,d,u,b){w['Bitrix24FormObject']=b;w[b] = w[b] || function(){arguments[0].ref=u;
(w[b].forms=w[b].forms||[]).push(arguments[0])};
if(w[b]['forms']) return;
var s=d.createElement('script');s.async=1;s.src=u+'?'+(1*new Date());
var h=d.getElementsByTagName('script')[0];h.parentNode.insertBefore(s,h);
})(window,document,'https://bistropechat.bitrix24.ru/bitrix/js/crm/form_loader.js','b24form');
b24form({"id":"5","lang":"ru","sec":"uwp5dl","type":"button","click":"", "presets": {"my_cookie1": "ValueChecked: " + radioValue }});

Select option remain selected after submit/refresh

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/

Dynamic dropdowns filtering options with jquery

I am trying to filter one dropdown from the selection of another in a Rails 4 app with jquery. As of now, I have:
$(document).ready(function(){
$('#task_id').change(function (){
var subtasks = $('#subtask_id').html(); //works
var tasks = $(this).find(:selected).text(); //works
var options = $(subtasks).filter("optgroup[label ='#{task}']").html(); // returns undefined in console.log
if(options != '')
$('#subtask_id').html(options);
else
$('#subtask_id').empty();
});
});
The task list is a regular collection_select and the subtask list is a grouped_collection_select. Both which work as expected. The problem is that even with this code listed above I can't get the correct subtasks to display for the selected task.
NOTE: I also tried var tasks=$(this).find(:selected).val() that return the correct number but the options filtering still didn't work.
Try something like this instead (untested but should work).
$(function () {
var $parent = $('#task_id'),
$child = $('#subtask_id'),
$cloned = $child.clone().css('display', 'none');
function getParentOption() {
return $parent.find('option:selected');
}
function updateChildOptions($options) {
$child.empty();
$child.append($options);
}
$parent.change(function (e) {
var $option = getParentOption();
var label = $option.prop('value'); // could use $option.text() instead for your case
var $options = $cloned.find('optgroup[label="' + label + '"]');
updateChildOptions($options);
});
});

Get value of asp.net CheckBox via jquery

I'm trying to load up a hidden field with a list of values from all checkboxes that are checked. Everything works fine except that the is(':checked') always returns false. Any ideas?
$('.invCheckBox').click(function () {
var cb = '';
var i = 0;
debugger;
$(".invCheckBox").each(function (index, element) {
debugger;
if ($(element).is(':checked')) {
alert($(element).attr('invNbr'));
if (i == 0) {
cb = $(element).attr('invNbr')
}
else {
cb = cb + ',' + $(element).attr('invNbr');
};
i = i + 1;
};
});
$('MainContent_txtHiddenField').text(cb);
});
Here is a fiddle for you might help :) http://jsfiddle.net/sAyfw/
$('.invCheckBox').change(function () {
$('.invCheckBox').each(function()
{
alert($(this).is(':checked'));
});
});
For whatever reason creating a CheckBox control server-side wraps the input tag in a span tag. Weird. So, I changed the code to create an HtmlInputCheckBox instead and now the jQuery works beautifully.
Dim divCheckBox As New HtmlGenericControl("div")
divCheckBox.Attributes.Add("style", "width: 95px; float: left;")
Dim chkCheckBox As New HtmlInputCheckBox
chkCheckBox.Attributes.Add("class", "invCheckBox")
chkCheckBox.Attributes.Add("invNbr", invoice.InvoiceNbr)
divCheckBox.Controls.Add(chkCheckBox)
divInvRow.Controls.Add(divCheckBox)
Thanks for the info about asp:CheckBox being wrapped in a span. My jQuery was always returning false, and I couldn't figure out why it was not working.
I used this:
console.log($(this).children(1).is(':checked'));
and that works perfectly with an asp:CheckBox.

Categories