Skip to content Skip to sidebar Skip to footer

How To Store Check Box Values Using Javascript Or Jquery?

I have multiple checkboxes. I have stored the checkbox values to the local storage, enabling the user to refresh the page and still have the checked or unchecked checkboxes display

Solution 1:

You can use .serialize() but you have to change the name atrribute's values.

$('button').click(function(){
  alert($('input').serialize());
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="checkbox"class="faChkRnd"name="likebox1"id="like"><inputtype="checkbox"class="faChkRnd"name="likebox2"id="like1"><inputtype="checkbox"class="faChkRnd"name="likebox3"id="like2"><inputtype="checkbox"class="faChkRnd"name="likebox4"id="like2"><button>getUrl</button>

The next step is to get the values from the QueryString and set the checkboxes.

It's should looks like this:

$.each(location.search.replace('?', '').split('&'), function(i, seg) {
   $('[name=' + seg.split('=')[0] + ']').attr('checked', 'checked');
});

http://jsbin.com/hecora/edit?html,js

Update

You can do "auto saving" when the user check/uncheck the checkboxes using hash or do pushState and add the params to the url (That's good in case from some reason you can't use the hash for this). Of course you need to check the browsers support first.

Example (of pushState):

var checkboxes = $('input[type="checkbox"]');
checkboxes.change(function() {
  var ser = '?' + checkboxes.serialize();
  history.pushState(null, null, ser);
});

$.each(location.search.replace('?', '').split('&'), function(i, seg) {
  $('[name=' + seg.split('=')[0] + ']').attr('checked', 'checked');
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="checkbox"class="faChkRnd"name="likebox1"id="like"><inputtype="checkbox"class="faChkRnd"name="likebox2"id="like1"><inputtype="checkbox"class="faChkRnd"name="likebox3"id="like2"><inputtype="checkbox"class="faChkRnd"name="likebox4"id="like2">

http://jsbin.com/nofoto/edit?html,js

Solution 2:

Using Jquery, based on this answer:

var checkArray = newArray(); 
$('input[type=checkbox]').each(function () {
    if (this.checked) checkArray.push(this.id)
});
var urlParameter = checkArray.join('&')

This would generate a string, containing the ids of all checked checkboxes. It works by iterating over all checkboxes on the page, saving the ids and then concatenating them with '&'. On loading the page you only have read the url parameters (e.g. http://website.com?checkbox1&checkbox2 would check checkbox1 and checkbox2) and check the boxes like you did with the local storage.

Solution 3:

$('input[type=checkbox]')

should use

$("input[type='checkbox'][name='likebox']").each( ...

Post a Comment for "How To Store Check Box Values Using Javascript Or Jquery?"