obi obi - 1 year ago 80
jQuery Question

How to stop sessionStorage from saving the values after a limit is reached

I've been trying to figure out how can I stop the sessionStorage from saving the values after the

is reached when the
Add Another Worker
button is clicked? It seems after the limit is reached and the button is clicked again the values keep getting added to the sessionStorage I was wondering how can I stop this from happening.

Here is a link to my jsfiddle


<div class="worker-container-last">
<label class="worker-label">
<select name="title[]" class="title">
<option value="Select a Title" selected="selected">Select a Title</option>
<option value="Boss">Boss</option>
<option value="Worker">Worker</option>
<option value="Manager">Manager</option>
<div class="add-more"></div>
<div><a class="worker" title="" href="">Add Another Worker</a></div>


var worker_record = [];
$('.worker').on('click', function(e){

var title = $('.title:first').val();

var someData = {title: title};

sessionStorage.worker = JSON.stringify(worker_record);

function workerData(){
var max_fields = 6;
var x = 1;

if(!(typeof sessionStorage.worker === 'undefined' || sessionStorage.worker.length<1)){
worker_record = JSON.parse(sessionStorage.worker);

for(var i=0; i<worker_record.length; i++){
if(x < max_fields){
var title = worker_record[i].title;

var worker = '<select name="title[]" class="title title-options"><option value="Select a Title" selected="selected">Select a Title</option><option value="Boss">Boss</option><option value="Worker">Worker</option><option value="Manager">Manager</option></select>';


$('.title:first').val('Select a Title');

Answer Source

To set a limit you can do this .

set a variable first

if (sessionStorage.getItem("limit") === null) {
    sessionStorage.setItem('limit', 0);

Increment the this variable value on every iteration and set a check of limit accordingly Suppose you want to set a limit = 10 then,

if(sessionStorage.getItem('limit') <= 10 )
 var count = sessionStorage.getItem('limit');

 sessionStorage.setItem('limit', count);

  //do whatever


   alert("session limit reached!");
   return false;


Working Demo

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download