how to store radio button value in sessionStorage with jquery - javascript

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

Related

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>

Materializecss - prop radio checkbox with jQuery on click

I have 1 radio item, and I want it to behave like a checkbox. So now, it gets selected but I couldn't bind it to prop state on click.
So I want to achieve is: when clicked on radio btn, it reverses its checked state.
Here is what I tried:
<form action="#">
<p>
<input name="group" type="radio" id="test" />
<label for="test">Red</label>
</p>
</form>
$(document).ready(function() {
$('#test').click(function() {
$('#test').prop('checked', !$('#test').prop('checked'))
})
})
What interesting is, if I create another button and bind it to change checked value, it works
<button id="faker" type="button">
Faker Btn
</button>
$('#faker').click(function() {
$('#test').prop('checked', !$('#test').prop('checked'))
})
Here is a fiddle: https://jsfiddle.net/55L52yww/81/
A radio can behave like a checkbox if you add a state attribute to the radio element like in:
<input name="group" type="radio" id="test" data-state="false"/>
Now, you can save the last state and compare with the current value in order to decide the action to do.
The snippet:
$('#test').on('click', function(e) {
var a = $(this).data('state');
var b = $(this).prop('checked');
if (a && b) {
b = false;
$(this).prop('checked', b);
}
$(this).data('state', b);
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<form action="#">
<p>
<input name="group" type="radio" id="test" data-state="false"/>
<label for="test">Red</label>
</p>
</form>
When you get into the function that was triggered by the radio button itself, the state of the checked property has already changed. That causes a problem on the first click, because the new state is true and therefore your function sets it back to false.
You can solve this by keeping track of the checked state yourself in a separate data attribute and checking that instead.
$(function() {
$('#test').click(function() {
var $this = $(this);
if ($this.data('previousState')) {
$this.prop('checked',false).data('previousState',false);
}
else {
$this.prop('checked',true).data('previousState',true);
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<form action="#">
<p>
<input name="group1" type="radio" id="test" />
<label for="test">Red</label>
</p>
</form>

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

save .addClass with jQuery cookie or local storage

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

Categories

Resources