I have taken the following snippet from a previously asked question on how to store the checked/unchecked status of all checkboxes on a page in localstorage:
$(function(){
var test = localStorage.input === 'true'? true: false;
$('[type="checkbox"]').prop('checked', test || false);
});
$('[type="checkbox"]').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
When I select one of the checkboxes and then refresh the page, once it reloads every single checkbox is checked.
How would I make this store each individual checked state?
Note I may have between 0 - 50 check boxes available depending on how many outstanding records there are in my gridview so I don't have fixed input id's to use only a record id associated to each row.
If you want to rely on a localStorage solution, you may do something like this:
$(function(){
$('[type="checkbox"]').each(function () {
var $this = $(this),
name = $this.attr('name');
$this.prop('checked', localStorage[name] === 'true');
});
});
$('[type="checkbox"]').on('change', function() {
var $this = $(this),
name = $this.attr('name');
localStorage[name] = $this.is(':checked');
});
http://jsfiddle.net/mct7xgq2/
The first part is executed on page load and sets the checked state depending on the localStorage[name] value, where name is the input's name attribute.
The second part executes when any checkbox is being changed: it takes the input's name, as before, but instead of reading the value, it writes it.
IF the page would not load, it would be better to just store the values in JS object rather than using localStorage .
Just create a JS object and keep pushing values inside it and store
Client Side Solution if the page does not reload
$(function(){
var checkedItems ={};
$('[type="checkbox"]').on('change', function() {
//Store the ID value also in the localstorage
if($(this).is(':checked')){
var id = $(this).attr('id'); //Get the id if this is checked
checkedItems['id_'+id] = id;
}
});
});
If Page reloads, then your best bet is to use server side concepts like Session.
Send an AJAX request each time a particular checkbox is checked and store it in a session.
SERVER SIDE SOLUTION
$(function(){
$('[type="checkbox"]').on('change', function() {
//Store the ID value also in the localstorage
if($(this).is(':checked')){
var id = $(this).attr('id'); //Get the id if this is checked
$.ajax({
type: 'POST',
url: your server side url path, //store it in a session
data: {'id':id},
dataType: 'html',
success: function(result){
//so some functionality
}
});
}
});
});
Check out the FIDDLE LINK
This is a solution for d3.js with a ternary operator use. It compares the id of this checkbox with the values stored under key=id in localStorage.
If the value is "true" then 'this.checked' is set to 'true', else to 'null' ( null indicates: no 'checked' property)
var box = d3.selectAll(".box").each(function(){
var id = this.id;
var storageValue = localStorage.getItem(id);
this.checked = storageValue === "true" ? true : null;
});
Previously I have setItem in localStorage. The checkbox are created dynamically appended to rows in a table
rows.append('input')
.attr('type','checkbox')
which in turn is based on the data from a cvs. With the following ids for the checkboxes:
.attr("id", function(d,i) { return 'box'+' '+i; })
And the 'change' of the checkbox state:
d3.selectAll(".box").on("change", function() {
var id = this.id;
if ( this.checked ){
localStorage.setItem(id, this.checked);
}
else {
localStorage.removeItem(id);
}
});
I have thousands of rows, each with a checkbox. I did not see a major issue on the timeline inspection. So I guess that this is a good solution. I am not a d3.js expert.
Related
I have a HTML from to capture string data. I am saving those when I hit the save button via ajax. But the scope also includes saving the data on a sessionstorage once I focus out of the form field with the orange save button after it checks the value is not empty. The idea is to pre populate each form field with values stored in the session storage. Everything works fine but I just cant figure out the session storage part. The hard part is how to assign a unique key for each form field, and use that key to find and preload values in the field.
Here is my JS
$('.wrapper').remove()
function renderInput() {
var inputField = '<div class="wrapper"><input class="zoom-text-field" type="text" value=""/><span class="close">save</span></div>';
return inputField;
}
function hideZoomFiled(e, textData) {
$(e).parent().parent().children('.students-name-collection').val(textData);
console.log(textData)
$(e).parent().hide();
$('.students-name-collection').attr('disabled', false);
$(e).prop('disabled', false);
}
function disableInputField(obj) {
$('.students-name-collection').attr('disabled', false);
$(obj).attr('disabled', true);
}
$('.students-name-collection').on('focus', function () {
disableInputField(this);
$(this).next('.wrapper').focus();
$('.wrapper').remove();
$(this).parent().append(renderInput());
var textData = '';
$('.close').on('click', function () {
textData = $(this).parent().children().val();
hideZoomFiled(this, textData);
});
$('.zoom-text-field').on('blur', function(){
if($(this).val() !== ''){
//save the value in the sessionstorage
//This is where I am getting lost
}
});
});
$('#submitForm').on('click', function(){
sessionStorage.clear();
})
// on page load read the session storage and pre fill the form fields
Here is my fiddle
http://jsfiddle.net/sghoush1/ykshgrxg/5/
Here is how you can handle this, as you pointed out the main problem here is how to figure out how to save each input item, and how to place it back when the page loads. What you can do is give each item an index, from 0 to 4.
To get the index of the element you are on, you can add an selected class to it, then use that class in order to find the elements position by using .index($('.selected')), of course we can remove that class when we are done with it. This can be used as the key for the sessionStorage, then the textData is the value:
// Get the index of the input item we are on
$(this).addClass("selected");
var key = $(".students-name-collection").index($('.selected'));
$(this).removeClass("selected");
$('.close').on('click', function () {
var textData = $(this).parent().children().val();
hideZoomFiled(this, textData);
if(!!textData){
//save the value in the sessionstorage
sessionStorage.setItem(key, textData);
}
});
Then for loading them in you can use jQuerys .each and have that on the class .students-name-collection using an index of sessionStorage to give each input the correct value:
// on page load read the session storage and pre fill the form fields
$('.students-name-collection').each(function(index) {
if(sessionStorage[index])
$(this).val(sessionStorage[index])
});
Here is a Fiddle Example
I have several checkboxes on my page that each correspond to different courses. When the user checks the checkbox I want to sent a POST request to the server to add details of their enrollment to the database.
I have the following jQuery to take note of the change:
$(function () {
$("input:checkbox").change(function () {
var fullURL = document.URL;
var url = fullURL.split('userID=');
var userID = url[1];
var courseID =
alert(userID + "and " + courseID);
$.post('/Admin/EnrolUser/', postData, function (data) {
});
});
});
On my page there are several checkbox inputs, how can I retrieve the value of the selected checkbox that fired the event and set this to the var courseID variable.
Every jQuery function that deals with collections set's the value of this to be the current element.
So...
$("input:checkbox").on("change", function(){
$(this).val(); //Element that fired event
});
Inside your change function the variable this represents your checkbox.
$("input:checkbox").change(function () {
var fullURL = document.URL;
var courseID = $(this).val();
alert(courseID);
});
jsfiddle here
I have the scripts below one which checks all checkboxes in a group which works great, and another to pass the checkbox values over the pagination and all works fine the only problem is that when I click the check all box it checks all the pages on page 1 but when I click page 2 only the check all box is checked although the query is working fine. If I click all the checkboxes individually then they pass through the pagination fine, so I don't know why the check all button doesn't. I would like it so that when you click check all, all the boxes stay checked through the pagination as well.
here is my script that checks all checkboxes
<script type="text/javascript">
window.addEvent('domready', function() {
$$('li.head input[type=checkbox]').addEvent('click', function() {
this.getParent('ul').getElements('input[type=checkbox]').setProperty('checked', this.checked);
});
});
</script>
here is the script that remembers the checkboxes
var aa_checkbox;
function init_checkbox(){
//setup blank cb cookie
if(!Cookie.read('cb')){
Cookie.write('cb', JSON.encode({}));
}
//setup "associative array" to match what is currently in the cookie
aa_checkbox = JSON.decode(Cookie.read('cb'));
//set up each checkbox with class="remember_cb"
$$('input.remember_cb').each(function(el){
//mark checked if it is in the cookie
if(aa_checkbox[el.name]){
el.checked = 'checked'
}
//setup onclick event to put checkbox status in the
el.addEvent('click', function(){
if(el.checked){
aa_checkbox[el.name] = 1;
}else{
delete(aa_checkbox[el.name]);
}
})
})
//save aa_checkbox back into cookie upon leaving a page
window.onbeforeunload = function(){Cookie.write('cb', JSON.encode(aa_checkbox));};
setup_form();
return true;
}
function setup_form(){
//set up form so that it adds the inputs upon submit.
$$('form.remember_cb_form').each(function(form){
form.addEvent('submit', function(ev){
//clean up previously inserted inputs
var aa_hidden_insert = $$('input.hidden_insert');
$each(aa_hidden_insert, function(el){
el.parentNode.removeChild(el);
})
var el_form = this;
//insert hidden elements representing the values stored in aa_checkbox
$each(aa_checkbox, function(i_value, s_name){
if(i_value){
var el_input = document.createElement('input');
el_input.type = 'hidden';
el_input.value = i_value;
el_input.name = s_name;
el_input.setAttribute('class', 'hidden_insert');
el_form.appendChild(el_input);
}
});
});
});
}
window.addEvent('domready', init_checkbox);
If anyone can help me I would be very greatful, Thanks
It has to do with how your code works. I recommend that the check/un-check should affect the in-memory copy of the backing data. EG if you have an array representing the check boxes, set the check/uncheck in the array then render the array to check/uncheck the corresponding check box. That way, when you check all, all the array cells are set to checked! When you change from page to page, simply read the status of the corresponding array cell.
I have a page with a list of id's and when an id is clicked, I have some code that pulls the value of that id:
$(document).on('click', '.show-editor', function(e){
e.preventDefault();
var editPath = $(this).find('a').attr('href');
var jOption = $(this).text();
How could I do this, in jQuery, for every id clicked on since the user got to the page? Also, the page doesn't refresh, it uses jQuery and Json.
* Revised Answer, since I now understand the question *
Depending on how long you want to keep them, your best bet seems like using sessionStorage.
Like so:
$('a').on('click',function(e){
if(typeof sessionStorge["ids"] !== "undefined"){
sessionStorage["ids"]=sessionStorage["ids"] + ', ' + this.id;
// be careful that all elements have an id (or that you don't mind undefined' all through your data)
} else {
sessionStorage['ids']=this.id;
}
})
Then To get all the data before the user leaves the page:
$(window).on('unload',function(e){
var arr=sessionStorage['ids'] || '';
arr=arr.split(',');
// now you have an array of these ids to do with as you please
})
Try this :
var id;
$("*").click(function(){
id= $(this).attr("id");
})
I know that there is the change event handling in jQuery associated with an input of type select. But I want to know if the user has selected another value in the select element ! So I don't want to run code when the user select a new element in the select but I want to know if the user has selected a different value !
In fact there are two select elements in my form and I want to launch an ajax only when the two select elements has been changed. So how to know that the two elements has been changed ?
You can specifically listen for a change event on your chosen element by setting up a binding in your Javascript file.
That only solves half your problem though. You want to know when a different element has been selected.
You could do this by creating a tracking variable that updates every time the event is fired.
To start with, give your tracking variable a value that'll never appear in the dropdown.
// Hugely contrived! Don't ship to production!
var trackSelect = "I am extremely unlikely to be present";
Then, you'll need to set up a function to handle the change event.
Something as simple as:-
var checkChange = function() {
// If current value different from last tracked value
if ( trackSelect != $('#yourDD').val() )
{
// Do work associated with an actual change!
}
// Record current value in tracking variable
trackSelect = $('#yourDD').val();
}
Finally, you'll need to wire the event up in document.ready.
$(document).ready(function () {
$('#yourDD').bind('change', function (e) { checkChange() });
});
First of all you may use select event handler (to set values for some flags). This is how it works:
$('#select').change(function () {
alert($(this).val());
});
Demo: http://jsfiddle.net/dXmsD/
Or you may store the original value somewhere and then check it:
$(document).ready(function () {
var val = $('#select').val();
...
// in some event handler
if ($('#select').val() != val) ...
...
});
First you need to store previous value of the selected option, then you should check if new selected value is different than stored value.
Check out the sample!
$(document).ready(function() {
var lastValue, selectedValue;
$('#select').change(function() {
selectedValue = $(this).find(':selected').val();
if(selectedValue == lastValue) {
alert('the value is the same');
}
else {
alert('the value has changed');
lastValue = selectedValue;
}
});
});
You can save the value on page load in some hidden field.
like
$(document).ready(function(){
$('hiddenFieldId').val($('selectBoxId').val());
then on change you can grab the value of select:
});
$('selectBoxId').change(function(){
var valChng = $(this).val();
// now match the value with hidden field
if(valChng == $('hiddenFieldId').val()){
}
});
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
http://docs.jquery.com/Events/change