Okay so I have been working on this code forever and I still cant get it to work right. I'm having two issues with my code.
I'm trying to save the values for each input and select field and display them again when the page is refreshed.
Every time a user types into the same input field a new
key: value
pair is created. I just want the same input field the user is typing into to update thesessionStorage
in real time when the user changes its value.
If it helps I'm using JQuery and PHP. My JQuery code is located below
JQuery
$(document).ready(function(){
var max_fields = 5;
var x = 1;
if(typeof(Storage) !== 'undefined'){
$('.worker').on('click', function(e){
e.preventDefault();
e.stopPropagation();
if(x < max_fields){
x++;
$(this).closest('li').find('div:eq(3)').append('<input type="text" name="first_name[]" class="first-name" /><input type="text" name="last_name[]" class="last-name" /><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></select>');
sessionStorage.setItem('Data',$(this).closest('li').find('div:eq(3)').html());
}
});
if(sessionStorage.getItem('Data')){
$('.worker').closest('li').find('div:eq(3)').html(sessionStorage.getItem('Data'));
}
}
});
var worker_record = [];
$(document).ready(function(){
$('.worker').closest('li').find('div:eq(3)').on('input', function(){
var fname = $('.first-name').val();
var lname = $('.last-name').val();
var wtitle = $('.title').val();
var worker_data = {first_name: fname, last_name: lname, title: wtitle};
worker_record.push(worker_data);
for(var i=0; i<worker_record.length; i++){
sessionStorage.newWorker = JSON.stringify(worker_record);
}
});
});
HTML
<ul>
<li>
<div class="worker-container">
<label class="worker-label"><input type="text" name="first_name[]" class="first-name" /></label>
</div>
<div class="worker-container">
<label class="worker-label"><input type="text" name="last_name[]" class="last-name" /></label>
</div>
<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>
</select>
</label>
</div>
<div class="add-more"></div>
<div><a class="worker" href="">Add Another Worker</a></div>
</li>
</ul>
Here is a link to my jsfiddle https://jsfiddle.net/qjp6uscu/