save .addClass with jQuery cookie or local storage - javascript

I'm trying to save the .addClass every time I save a stylesheet so that the button remembers
The user can toggle the option on/off.
My simple html:
<div id="btn-switch" class="btn-group" data-toggle="buttons">
<button class="btn btn-default" type="radio" name="options" id="option1" data-color="{T_THEME_PATH}/normal.css" autocomplete="off">off</button>
<button class="btn btn-default" type="radio" name="options" id="option2" data-color="{T_THEME_PATH}/inverse.css" autocomplete="off">on</button>
</div>
This is my code:
<script>
$(document).ready(function() {
if ($.cookie("css")) {
$("#bg").attr("href", $.cookie("css"));
}
$("#btn-switch button").click(function() {
$("#bg").attr("href", $(this).attr('data-color'));
$("#btn-switch .active").removeClass("active");
$(this).addClass("active");
$.cookie("css", $(this).attr('data-color'), {
expires: 365,
path: '/'
});
return false;
});
});
</script>
How can use the same cookie to save the .active class?
I would also use local storage for all of this but I dont know how to even start the code snippet I achieved above

Here is a way to use localstorage:
Given this markup (I am using input type="radio" for this example):
<div class="btn-group" data-toggle="buttons" id="btn-switch">
<label class="btn btn-default">
<input type="radio" id="option1" name="options" value="1" data-color="{T_THEME_PATH}/normal.css" autocomplete="off"> off
</label>
<label class="btn btn-default">
<input type="radio" id="option2" name="options" value="2" data-color="{T_THEME_PATH}/inverse.css" autocomplete="off"> on
</label>
</div>
<br><br>
<a id="bg" href="{T_THEME_PATH}/normal.css">Background</a>
In the script, listen for the change event on the radio buttons. This is fired for any radio that is checked. First set the #bg href to the clicked radio's color data-attribute (Use jQuery .data()). Then store this href to localstorage. Additionally store the ID of the clicked option to localstorage. Then on subsequent page loads use the items in localstorage to set the correct href and activate the correct radio button:
$(document).ready(function() {
var csshref = localStorage["css"];
if (csshref) {
$("#bg").prop("href", csshref);
}
var activeid = localStorage["activeid"];
if (activeid) {
$("#" + activeid).prop("checked", true).closest("label").addClass("active");
}
$('#btn-switch [type="radio"]').on("change", function() {
$("#bg").attr("href", $(this).data('color'));
localStorage.setItem('css', $(this).data('color'));
localStorage.setItem('activeid', $(this).prop('id'));
return false;
});
});
Here is a DEMO
In the demo, try checking on and off and then hittin RUN again. You will see that subsequent runs remember which item was checked and set the href appropriately.

Here is a simple way to do it:
$(document).ready(function () {
//on page load check for cookie value and add active class
if($.cookie("isButtonActive") == 1)
{
$("#btn-switch button").addClass("active");
}
$("#btn-switch button").click(function() {
//your previous code here
if($("#btn-swtich button").hasClass("active") == true)
{
//button was active, de-activate it and update cookie
$.("#btn-switch button").removeClass("active");
$.cookie("isButtonActive", "0");
}
else
{
//button is not active. add active class and update cookie.
$.("#btn-switch button").addClass("active");
$.cookie("isButtonActive", "1");
}
});
});

Related

How add attribute to radio element on new items?

The code can add attribute checked="checked" on first item already loaded from HTML markup. But, when I added a new "item" radio element, the code cannot include the attribute checked="checked". Why this happens?
I tested using the browser console (F12) to see if attribute would be included or not on respective radio input clicked, but no success so far.
If I not add checked="checked" my value is not stored on sql table. But if I add checked="checked" manually, editing on my browser console, my value is updated with success on sql table.
How can I fix this situation?
jsfiddle
<div id="p_scents">
<p>
<span class="custom_radio">
<input type="radio" id="featured-1" name="s_radio" value="1"> <label for="featured-1">item 1</label>
</span>
</p>
</div>
<span id="add" class="btn btn-sm btn-primary">add</span>
<span id="remove" class="btn btn-sm btn-pub">remove</span>
var i = 1 ;
var scntDiv = $('#p_scents');
function add_track() {
if(i < 30){
i++;
$('<p><span class="custom_radio"><input type="radio" id="featured-'+ i +'" name="s_radio" value="'+ i +'"> <label for="featured-'+ i +'">item '+ i +'</label></span></p>').appendTo(scntDiv);
}
}
function remove_track() {
if(i > 1){
var select = document.getElementById('p_scents');
select.removeChild(select.lastChild);
i--;
}
}
document.getElementById('add').addEventListener('click', add_track, false);
document.getElementById('remove').addEventListener('click', remove_track, false);
$("[name='s_radio']").on("click", function() {
$("[name='s_radio']").attr("checked", false);
$(this).attr("checked", true);
});
Let me clarify few things here so you actually learn something:
you are writing the JS code for something HTML radio buttons do them self's. If you put same name attribute in your case name="s_radio" on them they will automatically uncheck others and just live check on the only clicked one, they just need to have same name, and you already did that. This is called grouping inputs:
Example:
var i = 1 ;
var scntDiv = $('#p_scents');
function add_track() {
if(i < 30){
i++;
$('<p><span class="custom_radio"><input type="radio" id="featured-'+ i +'" name="s_radio" value="'+ i +'"> <label for="featured-'+ i +'">item '+ i +'</label></span></p>').appendTo(scntDiv);
}
}
function remove_track() {
if(i > 1){
var select = document.getElementById('p_scents');
select.removeChild(select.lastChild);
i--;
}
}
document.getElementById('add').addEventListener('click', add_track, false);
document.getElementById('remove').addEventListener('click', remove_track, false);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="p_scents">
<p>
<span class="custom_radio">
<input type="radio" id="featured-1" name="s_radio" value="1"> <label for="featured-1">item 1</label>
</span>
</p>
</div>
<span id="add" class="btn btn-sm btn-primary">add</span>
<span id="remove" class="btn btn-sm btn-pub">remove</span>
So your JS code is complicity unnecessary as HTML will do this for you alone... And it was clearly stated in comments.
You are adding your JS click event listener on page load and it creates a list of elements on page load. You are adding more of them with button and they will not be included in that list. So solution is to bound listener on document itself and when clicked it will check for all elements with added selector.
So do not use $("[name='s_radio']").on("click", function() { where you target just already loaded [name='s_radio'] radios
Use $("document").on("click", "[name='s_radio']", function() { where you will bind document and on click it will check for all [name='s_radio'], new or old. By new I talk about dynamically added with button.
So people do not have problems with radio buttons, Id say radios have problem with some people. And browser IS your friend. You just need to learn to use it.
This should solve the problem
$(document).on('click',"[name='s_radio']",function (e) {
$("[name='s_radio']").attr("checked", false);
$(this).attr("checked", true);
})

disable button in jquery on checkbox

If a user checked on the checkbox then the button should be enabled. If not then button should be disabled.
function test(){
if($(this).val() === true){ //not working
$('#send_button').prop('disabled', false);
}
else if($(this).val() === false){
$('#send_button').prop('disabled', true);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<input id="ischeck" type="checkbox" name="ischeck" value=true>
<label for="ischeck">ischeck</label><br>
<button id="send_button" class="btn btn-primary pull-right" onclick="test()">Send</button>
You should add an event listener on the input checkbox dom element in order to catch the value change like this (check the documentation here):
$("#ischeck").change(...);
Then, check which value the input has, and set the button disabled property accordingly:
$('#send_button').prop('disabled', !this.checked);
Note: Do not forget for the case of checkbox input type, in order to set the initial value, you should use the property checked like this (more info here):
<input id="ischeck" type="checkbox" name="ischeck" checked=true>
Follows a full working example:
$("#ischeck").change(function () {
// You want to se the property disable of the send button with the oposite value of the input;
// Example: Input: true [then] Button disabled: false
$('#send_button').prop('disabled', !this.checked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<input id="ischeck" type="checkbox" name="ischeck" checked=true>
<label for="ischeck">ischeck</label><br>
<button id="send_button" class="btn btn-primary pull-right" onclick="test()">Send</button>

Select all checkbox only works some of the time

I have a form with checkboxes, along with a hidden select all button inside the form. I use jQuery to listen for a button click outside the form, and then "click" the hidden button element to select all. Sometimes the page loads up and I click the button and it works perfectly. You can click it multiple times and they all check and uncheck as intended. The form submits perfectly.
Other times, however, the page will load up and I click the button and nothing happens. They don't check no matter how many times I click. I've found this happens a lot if the page sits for more than maybe 10 seconds without me doing anything. But it also can happen on page load. I can't understand why. Is there an error in my code somewhere that I'm just not seeing?
$(document).ready(function(){
$('#select-all').click(function(event) {
if(this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
$('label.choice').toggleClass("choice-text-color");
});
} else {
$(':checkbox').each(function() {
this.checked = false;
$('label.choice').toggleClass("choice-text-color");
});
}
});
$("#selectAll").click(function() {
$('#select-all').click()
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="selectAll" class="btn btn-secondary my-2 my-sm-0"
type="button" name="selectAll">Select All</button>
<form>
<input type="checkbox" id="1"><label for="1" class="choice">ABC</label>
<input type="checkbox" id="2"><label for="2" class="choice">DEF</label>
(....etc.....)
<input type="checkbox" id="select-all" style="display: none;">
<input type="submit" style="display: none;">
</form>
It seems to me that your issue is due to the extraneous markup you've added to facilitate the select all functionality and the JavaScript/JQuery tied to it.
All you need is a single button (it doesn't matter whether it's part of the form or not) to trigger the select/deselect operations. Also, since the button will not be transmitting any data as part of the form the name attribute should not be used.
Also, if you don't want users to see the form's submit button, then simply don't add one to the form. You can then programmatically submit the form with $(form).submit().
// Passing a function into JQuery is the same as document.ready
$(function(){
// JQuery recommends the use of "on" to bind events
$('#selectAll').on("click", function(event) {
$(':checkbox').each(function() {
this.checked = true;
});
$('label.choice').addClass("choice-text-color"); // Update the class use
});
});
.choice-text-color {
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="selectAll" class="btn btn-secondary my-2 my-sm-0" type="button">Select All</button>
<form>
<input type="checkbox" id="1"><label for="1" class="choice">ABC</label>
<input type="checkbox" id="2"><label for="2" class="choice">DEF</label>
</form>

how to store radio button value in sessionStorage with jquery

I have radio button in my navbar and I want to store its value for one session or I can say it automatically retains the same value as user visits different pages of website but resets when browser or tab is closed. What I found is sessionStorage and I tried it but unfortunately its not working, here is my code
<lab
console.log($('[type=radio]').length);
$("#option1").click(function() {
console.log('I am inside radio type'+this.value);
sessionStorage.setItem('option', this.value);
});
$("#option2").click(function() {
console.log('I am inside radio type'+this.value);
sessionStorage.setItem('option', this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- <div class="btn-group btn-group-toggle" data-toggle="buttons"> -->
<!-- <label class="btn btn-secondary active"> -->
<input type="radio" value="shop" name="option" id="option1">option1
<!-- </label> -->
<!-- <label class="btn btn-secondary"> -->
<input type="radio" value="product" name="option" id="option2">option2
<!-- </label> -->
<!-- </div> -->
el class="btn btn-secondary active">
Option1
Option2
In script what I tried is
$('[type=radio]').click(function() {
var value = $('[name="option"]').val();
sessionStorage.setItem('option',value);
});
console.log(sessionStorage.getItem('option'));
Its only printing option1 every time and is it the right way what I want to achieve ?
The type value needs to be formatted as a string with quotes around it, like below:
$('input[type="radio"]').click(function() {
console.log('I am inside radio type');
sessionStorage.setItem('option', this.value);
});
And if you're loading these buttons dynamically/after loading the script, you can attach the listener to the document object instead:
$(document).on('click', 'input[type="radio"]', function() {
console.log('I am inside radio type');
sessionStorage.setItem('option', this.value);
});
Inside the click event store the value of checked radio button as follows,
$(function() {
alert(sessionStorage.getItem('option'));
$('[type=radio]').click(function() {
alert(this.value); sessionStorage.setItem('option',this.value);
});
});

checkbox change not fired at page load time

I have a button and checkbox(terms of use) in my page.
The button should be disabled if the checkbox is not checked.
I want to reset the situation in every load. (first load or using back btn or etc) the reset state is: checkbox shouldn't be checked, and btn is disabled.
But the function is called just when I click the checkbox, and not at load time.
Update: Also I tested .trigger('change'), too. It did't work too
$(function() {
$('#termsOfUse').removeAttr('checked');
$('#termsOfUse').change();
$('#termsOfUse').change(function() {
if ($(this).is(":checked")) {
$('#createBtn').prop('disabled', false);
} else {
$('#createBtn').prop('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<input id="termsOfUse" type="checkbox" />
<label for="termsOfUse" style="display: inline;">
<span>rules</span> I am agree with</label>
</div>
<div class="create">
<input id="createBtn" type="button" value="create" class="btn btn-default btn-success"
onclick="location.href = '#Url.Action("Create","NewOne ")'" />
</div>
You are calling the .change before you assign.
$(function() {
$('#termsOfUse').prop('checked',false);
$('#termsOfUse').change(function() {
$('#createBtn').prop('disabled', !this.checked);
}).change(); // execute at load
});
You can also put
<script>
$('#termsOfUse').prop('checked',false);
$('#termsOfUse').change(function() {
$('#createBtn').prop('disabled', !this.checked);
}).change(); // execute at load
</script>
</body>
at the end of your document

Categories

Resources