How to make cookie with multiple values in jQuery - javascript

I am having some trouble creating and getting a cookie with multiple values inside.
Okay, what I would like to do, is to create a cookie with a forms input values in it when a submit button is clicked. Then when the same user revisits the site, the form will be autofilled with what the user typed in last time.
My html:
<form id="formen">
<fieldset>
<legend>Login</legend>
<label for="firstname" class="label">Firstname</label>
<input type="text" name="firstname" id="firstname" class="text" maxlength="30" />
</br></br>
<label for="lastname" class="label">Lastname</label>
<input type="text" name="lastname" id="lastname" class="text" maxlength="30" />
</br></br>
<label for="lastname" class="label">Address</label>
<input type="text" name="third" id="address" class="text" maxlength="30" />
</br></br>
<label for="lastname" class="label">City</label>
<input type="text" name="city" id="city" class="text" maxlength="30" data-sayt-exclude/>
</br></br>
<label for="lastname" class="label">Zipcode</label>
<input type="number" name="zipcode" id="zipcode" class="text" maxlength="30" />
</br></br>
<label for="lastname" class="label">E-mail</label>
<input type="email" name="email" id="email" class="text" maxlength="30" />
</br></br>
<label for="lastname" class="label">Phone</label>
<input type="number" name="phone" id="phone" class="text" maxlength="30" />
</br></br>
<input type="submit" name="submit" value="Remember Me" id="remember"/>
</fieldset>
</form>
My javascript/jQuery:
$(document).ready(function () {
var date = new Date();
date.setTime(date.getTime() + (60 * 1000));
if ($("#remember").click(function () {
$.cookie('firstnameCookie', $firstnameVariable.val(), { expires: date });
$.cookie('lastnameCookie', $lastnameVariable.val(), { expires: date });
$.cookie('addressCookie', $addressVariable.val(), { expires: date });
$.cookie('cityCookie', $cityVariable.val(), { expires: date });
$.cookie('zipcodeCookie', $zipcodeVariable.val(), { expires: date });
$.cookie('emailCookie', $emailVariable.val(), { expires: date });
$.cookie('phoneCookie', $phoneVariable.val(), { expires: date });
}));
//set the value of the cookie to the element
var $firstnameVariable = $("#firstname").val($.cookie("firstnameCookie"));
var $lastnameVariable = $("#lastname").val($.cookie("lastnameCookie"));
var $addressVariable = $("#address").val($.cookie("addressCookie"));
var $cityVariable = $("#city").val($.cookie("cityCookie"));
var $zipcodeVariable = $("#zipcode").val($.cookie("zipcodeCookie"));
var $emailVariable = $("#email").val($.cookie("emailCookie"));
var $phoneVariable = $("#phone").val($.cookie("phoneCookie"));
});
This code actually does the trick. It saves the different input values, and autofills when user revisits the site.
The only problem is that I don't want to create a new cookie for each input value.
Is it possible to create just one cookie with each of the inputs values in it, and get it to autofill the different input fields?
Hope someone can help me! Can't figure it out..
Thx

Concatenate the form values into a string before saving the cookie and split when you have to assign it.
Those are functions I use to concatenate and split:
var splitQueryString = function (q) {
var pars = q.split("&");
var qq = {};
var i = 0;
for (i = 0; i < pars.length; i++) {
var ret = pars[i].toString().split("=");
qq[ret[0]] = decodeURIComponent(ret[1]);
}
return qq;
};
var getQueryString = function (pars) {
var q = '';
var value;
var key;
for (key in pars) {
if (pars.hasOwnProperty(key)) {
value = pars[key];
if (!(value === null)) {
q += "&" + key + "=" + encodeURIComponent(value);
}
}
}
if (q.length > 0) {
//remove first
q = q.substr(1);
}
return q;
};
Your code could become something like:
if ($("#remember").click(function () {
var pars = {};
pars.firstnameVariable = $firstnameVariable.val();
pars.lastnameVariable = $lastnameVariable.val();
var cookie = getQueryString(pars);
$.cookie('formCookie', cookie, { expires: date });
}));
//set the value of the cookie to the element
var pars = splitQueryString($.cookie("formCookie"));
var $firstnameVariable = $("#firstname").val(pars.firstnameVariable);
var $lastnameVariable = $("#lastname").val(pars.lastnameVariable);

Store the data by converting the object to a string
var obj = {
"firstname" : $("#firstname").val(),
"lastname" : $("#firstname").val()
};
$.cookie('data', JSON.stringify(obj), { expires: date });
And when you read it out:
var data = $.cookie("data"),
obj = data ? JSON.parse(data) : "";
Object.keys(obj).forEach(function(key){
$("#" + key).val(obj[key]);
});
Personally I would use localstorage and not a cookie.

Related

Double Square Brackets in my Javascrip Arrays within localStorage?

I have managed to get data registering to my localStorage as arrays, however I have three queries:
Why are there double square brackets around my array?
How do I change the name field to the respective html ID?
Data returning as undefined when I try to retrieve it from the localStorage?
The output I am looking for in my localStorage is:
bookings: [
[0]{fname: "John", lname: "Smith" }
[1]{fname: "Jane", lname: "Doe" }
]
But I am currently getting:
bookings: [
[0][{name: "fname" value: "John"},{name: "lname": value: "Smith" }]
[1][{name: "fname" value: "Jane"},{name: "lname": value: "Doe" }]
]
I understand how to change the name value when items are hardcoded but I am initialising an empty array in my JS and not sure where the error is, I have tried assigning a value to the array [0] but then it doesn't register anything. I have also tried the data.flat() method which does nothing.
The issue is my next step is to amend and delete items so I need to try and understand the structure. Currently I am getting undefined when I try to get data from storage, I have provided my remove function (currently to show) below, I know it is wrong but I think the issue is to do with how I am storing the data. Sorry I have asked so many questions on this but I am new to JS and still learning. I am struggling with searches as there are so many variations of Javascript and getting a lot of answers relating to C# or Python which isn't helping.
Here is my code:
//var bookings = [];
var bookings = localStorage.getItem("bookings");
$("#submit").click(function () {
//bookings = JSON.parse(localStorage.getItem("bookings")) || [];
bookings = (bookings) ? JSON.parse(bookings) : [];
var newBooking = $("#regForm").serializeArray();
bookings.push(newBooking)
var json = JSON.stringify(bookings);
const newData = bookings.flat();
window.localStorage.setItem("bookings", json);
});
$("#remove").click(function () {
var strBookings;
var i;
strBookings = localStorage.getItem("bookings");
//document.write("<p>" + strBookings + "</p>");
bookings = JSON.parse(strBookings);
for (i = 0; i < strBookings.length; i++) {
document.write("<p>" + strBookings[i].value + "</p>");
}
//localStorage.removeItem('bookings');
});
Form
<form id="regForm" name="regForm" class="col-sm-6">
<div class="row">
<input type="text" id="fname" placeholder="First Name" name="fname" required>
<input type="text" id="lname" placeholder="Last Name" name="lname" required>
<input id="submit" type="submit" value="Submit">
</div>
</form>
Show
//var bookings = [];
var bookings = localStorage.getItem("bookings");
$("#submit").click(function () {
//bookings = JSON.parse(localStorage.getItem("bookings")) || [];
bookings = (bookings) ? JSON.parse(bookings) : [];
var newBooking = $("#regForm").serializeArray();
bookings.push(newBooking)
var json = JSON.stringify(bookings);
const newData = bookings.flat();
window.localStorage.setItem("bookings", json);
});
$("#remove").click(function () {
var strBookings;
var i;
strBookings = localStorage.getItem("bookings");
//document.write("<p>" + strBookings + "</p>");
bookings = JSON.parse(strBookings);
for (i = 0; i < strBookings.length; i++) {
document.write("<p>" + strBookings[i].value + "</p>");
}
//localStorage.removeItem('bookings');
});
<form id="regForm" name="regForm" class="col-sm-6">
<div class="row">
<input type="text" id="fname" placeholder="First Name" name="fname" required>
<input type="text" id="lname" placeholder="Last Name" name="lname" required>
<input id="submit" type="submit" value="Submit">
</div>
</form>
<button id="remove" value="Remove">Show</button>

Prevent localstorage from saving if input is required but not filled?

I have this code im making, and im wondering if i could prevent the localstorage from saving unless the required inputs in my form is filled out correctly. Right now the localstorage works with my submit button, but still saves if it gives me the "Please fill this field" message. Any help would be appriciated ! Here is the function i use to save the data.
let writeDate = () => {
if (isLocalStorageEnabled) {
$("confirmBtn").addEventListener("click", () => {
let getItem = localStorage.getItem('bookingDate');
let bookingDate = getItem ? JSON.parse(getItem) : [];
let bk = Object.assign({}, bookingInfo);
bk.name = $("fname").value;
bk.amount = $("famount").value;
bk.date = $("fdate").value;
bk.time = $("ftime").value;
bookingDate.push(bk);
let date = JSON.stringify(bookingDate);
localStorage.setItem("bookingDate", date);
});
};};
Toby, you can implement it as following.
I tried to keep variable name as same as your question.
html
<div>
<form onsubmit="return onSubmit(event)">
<label for="fname">Name:
<input type="text" id="fname" name="fname" required />
</label>
<label for="famount">Amount:
<input type="number" id="famount" name="famount" required />
</label>
<label for="fdate">Date:
<input type="date" id="fdate" name="fdate" required />
</label>
<label for="ftime">Time:
<input type="time" id="ftime" name="ftime" required />
</label>
<button type="submit">Confirm</button>
</form>
</div>
javascript
const onSubmit = (e) => {
e.preventDefault()
const prevBookingDate = localStorage.getItem('bookingDate');
let bookingDate = prevBookingDate ? JSON.parse(prevBookingDate) : [];
const { fname, famount, fdate, ftime } = e.target
const bk = {
name: fname.value,
amount: famount.value,
date: fdate.value,
time: ftime.value
};
bookingDate.push(bk);
let date = JSON.stringify(bookingDate);
localStorage.setItem("bookingDate", date);
}

Get data for form input array using specific key

So, let's say I have an HTML form like this:
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
And I want to get a JavaScript array that matches the values of real. For example:
// If there was a sweet function for this...
var people = getFormDataByInputName( 'people' );
// Value of `people` is...
// [
// {
// 'first_name' : 'John',
// 'last_name' : 'Doe'
// },
// {
// 'first_name' : 'Jane',
// 'last_name' : 'Smith'
// }
// ]
Is there any easy way of doing that for just a specific form item (in this case, people)? Or would I have to serialize the entire form an then just extract the element I want?
I also thought of potentially using the following approach:
var formData = new FormData( document.querySelector( '#myForm' ) );
var people = formData.get( 'people' );
But that doesn't appear to work; people is just null after that.
You could do this with plain js using reduce method and return each person is one object.
const form = document.querySelectorAll('#myForm input');
const data = [...form].reduce(function(r, e) {
const [i, prop] = e.name.split(/\[(.*?)\]/g).slice(1).filter(Boolean)
if (!r[i]) r[i] = {}
r[i][prop] = e.value
return r;
}, [])
console.log(data)
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
function getObject(name, key) {
if(key.includes(name)) {
var splitStr = key.split(/\[|\]/g);
return {
index: splitStr[1],
key: splitStr[3],
}
}
return null;
}
function getFormDataByInputName(name) {
var formData = new FormData( document.querySelector('#myForm'));
var results = [];
for (var key of formData.keys()) {
var obj = getObject(name, key);
if (obj) {
if (results[obj.index]) results[obj.index][obj.key] = formData.get(key);
else results[obj.index] = { [obj.key]: formData.get(key) };
}
}
return results;
}
var people = getFormDataByInputName('people');
console.log(people);
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
Your code won't work because to HTML/JS name is just a string that it sends to the server when the form is submitted (the name in the name/value pairs). You might think it is arrays, but HTML/JS doesn't.
So no one-liner to get the job done. Try this: In your HTML, add <div class="name"> ...
(UPDATE: thanks for the idea, #Nenad, I've never tried one of these snippets)
var people = [];
$('.name').each(function() {
people.push({
first_name: $('input:nth-child(1)', this).val(),
last_name: $('input:nth-child(2)', this).val()
});
});
console.log(people);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="text" name="dummy">
<div class="name">
<input type="text" value="John">
<input type="text" value="Doe">
</div>
<div class="name">
<input type="text" value="Jane">
<input type="text" value="Smith">
</div>
</form>
Use CSS attribute prefix selector, such as
form.querySelectorAll('[name^="people[]"]')
You can use a for-loop to get all peoples, as such
const MAX_PEOPLES = 2;
const list = [];
for (i = 0; i <= MAX_PEOPLES; i++) {
const eles = form.querySelectorAll(`[name^="people[${i}]`);
if (eles.length !== 2)
break;
list.push({
first_name: eles[0].value,
last_name: eles[1].value
});
}
that yields
[
{
"first_name":"John",
"last_name":"Doe"
},
{
"first_name":"Jane",
"last_name":"Smith"
}
]

How to convert the input name dot to json format in simple way?

I have used the struts json plugin and tried to convert the form data to json format to submit by ajax.
I have two cases in the HTML
<form>
<input type="text" name="user.name" value="Tom"></p>
<input type="text" name="user.location" value="China"></p>
<input type="text" name="user.data[0].id" value="993"></p>
<input type="text" name="user.data[0].accountId" value="123"></p>
<input type="text" name="user.data[1].id" value="222"></p>
<input type="text" name="user.data[1].accountId" value="333"></p>
</form>
What I expected is to convert it to the json structure:
{
user : {
name: "Tom",
location : "China",
data: [
{
id : 993,
accountId : 123
},
{
id : 222,
accountId : 333
}
]
}
}
I know how to declare the json data and declare the attributes one by one.
I would like to have the better way to make each form to be in json format using simple way rather than declaring the parameter one by one in json format.
Appreciate for any suggestion or advice. Thank you.
Provided your form is exactly like that
Using a plain JS approach
<form class="userform">
<input type="text" class="username" value="Tom"></p>
<input type="text" class="userlocation" value="China"></p>
<input type="text" class="userid" value="993"></p>
<input type="text" class="useraccountid" value="123"></p>
<input type="text" class="userid2" value="222"></p>
<input type="text" class="useraccountid2" value="333"></p>
</form>
Then assign the values to the object
var frm = document.getElementsByClassName('userform');
//initialize blank object and keys
var user = {},
user.name = "",
user.location = "",
user.data = [];
//get all child input elements
for(var i = 0; i < frm.length; i++){
var uname = frm[i].getElementsByClassName('username')[0];
var uloc = frm[i].getElementsByClassName('userlocation')[0];
var uid = frm[i].getElementsByClassName('userid')[0];
var uaccid = frm[i].getElementsByClassName('useraccountid')[0];
var uid = frm[i].getElementsByClassName('userid2')[0];
var uaccid = frm[i].getElementsByClassName('useraccountid2')[0];
//assign values to object here
user[name] = {}; //assigning a parent property here, the name for example.
user[name].name = uname.value;
user[name].location = uloc.value;
user[name].data.push({
'id': uid.value
'accountId': uaccid.value
});
user[name].data.push({
'id': uid2.value
'accountId': uaccid2.value
});
}
JSON.stringify(user); //convert to JSON (or ignore if you want a plain object)
Output would be this in JSON format
{
user :{
Tom: {
name: "Tom",
data: [
{
id : 993,
accountId : 123
},
{
id : 222,
accountId : 333
}
]
},
Jerry: {
//more data
},
Courage: {
//more data
}
}
}
Hope this helps
If your input fields are many, like id3, accountid3, 4, 5, 6. You have to loop through the classes that you assign to these two repetitive fields
Here you go with a solution using jQuery https://jsfiddle.net/pnz8zrLx/2/
var json = {};
$('button').click(function(){
$('form').each(function(i){
json["user" + i] = {};
json["user" + i].data = [];
var tempJSON = {};
$('form:nth-child(' + (i+1) + ') input[type="text"]').each(function(){
if($(this).attr('name') === 'name' || $(this).attr('name') === 'location'){
json["user" + i][$(this).attr('name')] = $(this).val();
} else {
tempJSON[$(this).attr('name')] = $(this).val();
if(tempJSON != {} && $(this).attr('name') === 'accountId'){
json["user" + i].data.push(tempJSON);
tempJSON = {};
}
}
});
});
console.log(json);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="name" value="Tom">
<input type="text" name="location" value="China">
<input type="text" name="id" value="993">
<input type="text" name="accountId" value="123">
<input type="text" name="id" value="222">
<input type="text" name="accountId" value="333">
</form>
<form>
<input type="text" name="name" value="Test">
<input type="text" name="location" value="Test112">
<input type="text" name="id" value="22">
<input type="text" name="accountId" value="78">
<input type="text" name="id" value="00">
<input type="text" name="accountId" value="44">
</form>
<button>
Submit
</button>
Hope this will help you.

Creating Id using javascript

I want to create staffid from three different textboxes values by getting their first letter & adding auto increment number atlast.
eg "staffname", "gender", "designation" result staffid: sgd01 & I want to auto display in the staff id textbox while staffid textbox is disabled. Here is the code below:
<input name="staffname" id="staffname" size="30" type="text" value placeholder=" Staff Name" onkeyup="quick()" class="formTxtInput">
Script
function quick() {
var gender = document.getElementById('gender').value;
var staffname = document.getElementById('staffname');
var desg = document.getElementById('desg').value;
var gen = gender.charAt(0);
var sn = staffname.charAt(0);
var dg = desg.charAt(0);
var val = gen + sn + dg;
document.getElementById('staffid').value = val;
}
You have a missing .value for var staffname. It should be
var staffname = document.getElementById('staffname').value;
Also your function needs to be called on every keyup on each of the 3 input boxes so that updated values can be processed
Here is a working sample: http://jsbin.com/vobikejejo/1/
Hope this helps :)
You can try by updating your function as below:
<script>
var num=01;
function quick() {
num+=1;
var gender = document.getElementById('gender').value;
var staffname = document.getElementById('staffname').value;
var desg = document.getElementById('desg').value;
var gen = gender.charAt(0);
var sn = staffname.charAt(0);
var dg = desg.charAt(0);
var val = gen + sn + dg + num;
document.getElementById('staffid').value = val;
}
By default there is no value, so it is not working. Try by setting the default value.
<input name="staffname" id="staffname" size="30" type="text" value="staffname" placeholder=" Staff Name" onkeyup="quick()" class="formTxtInput">
<input name="gender" id="gender" size="30" type="text" value="gender" placeholder=" Staff Name" class="formTxtInput">
<input name="desg" id="desg" size="30" type="text" value="desg" placeholder=" Staff Name"class="formTxtInput">
<input name="staffid" id="staffid" size="30" disabled="disabled" type="text" value placeholder=" Staff Name" class="formTxtInput">
YOu can view demo here 1

Categories

Resources