How to save user input to local storage - javascript

I am creating a score keeping app and need to save the name of the players and the game name in local storage, have no idea how to apply it to the code I have
$(document).ready(function() {
$("#add-playername").click(function(e) {
e.preventDefault();
var numberOfPlayernames = $("#form1").find("input[name^='data[playername]']").length;
var label = '<label for="data[playername][' + numberOfPlayernames + ']">Playername ' + (numberOfPlayernames + 1) + '</label> ';
var input = '<input type="text" name="data[playername][' + numberOfPlayernames + ']" id="data[playername][' + numberOfPlayernames + ']" />';
var removeButton = '<button class="remove-playername">Remove</button>';
var html = "<div class='playername'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-playername").before(html);
});
});
$(document).on("click", ".remove-playername", function(e) {
e.preventDefault();
$(this).parents(".playername").remove(); //remove playername is connected to this
$("#form1").find("label[for^='data[playername]']").each(function() {
$(this).html("Playername " + ($(this).parents('.playername').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form2" method="post">
<div class="gamename">
<label><b>Enter Game Name</b></label>
<input type="text" name="game name" placeholder="Game Name" id="user_input">
</div>
</form>
<form id="form1" method="post">
<div class="playername">
<label for="data[playername][0]">Add Player Name</label>
<input type="text" name="data[playername][0]" placeholder="Enter player's name" id="data[playername][0]" />
</div>
<button id="add-playername">Add Player</button>
<br>
<br>
<input type="submit" value="Submit" />
</form>

Grab game and players using the jquery selector on form submit by preventing the form using jquery
Prepare object for the game and players
Convert the object to a string using the JSON.stringify( your_data_object) function
Save to localStorage using localStorage.setItem( 'key' , 'value' ) function
<script>
$('#form1').submit(function(){
var game_name = $("#form2 #user_input").val();
var players = [];
var players_inputs = $("#form1").find("input[name^='data[playername]']");
$.each(players_inputs, function(){
var player = $(this).val();
players.push(player);
});
var data = {
game_name : game_name,
players: players
}
console.log(data);
// save to localstorage
localStorage.setItem('game_players', JSON.stringify(data) );
event.preventDefault();
});
</script>

late to answer but something like this
<input type="submit" value="Submit" id="btn_submit" />
<script type="text/javascript">
$(document).ready(function(){
$("#btn_submit").click(function(e){
e.preventDefault();
var jsonObj = [];
players = {}
count = 0;
$('input[type=text]').each(function(){
if($.trim($(this).val()) && ($(this).attr('name').indexOf("playername") >= 0)){
players[count++] = $(this).val()
}
});
players['game_name'] = $("#user_input").val();
jsonObj.push(players);
console.log(jsonObj);
var jsonString= JSON.stringify(jsonObj);
localStorage.setItem("jsonString", jsonString);
/* remove localstorage */
// localStorage.removeItem("jsonString");
/* get localstorage */
// console.log(localStorage.getItem("jsonString"));
});
</script>

Related

How clear the form inputs after submission?

Already tried everything from different references but, I can't get it to work. I intended to use it for google photo submission form. I just want my text inputs and textarea to clear after it successfully uploaded everything.
Here's the whole HTML code.
<form id="uploaderForm">
<label for="uploaderForm">Photo Upload Form</label>
<div>
<input type="text" name="applicantName" id="applicantName"
placeholder="Your Name">
</div>
<div>
<input type="text" name="gradesection" id="gradesection"
placeholder="Your Grade Level & Section">
</div><br>
<div>
You can select multiple Photos upload!<br>
<br>
<input type="file" name="filesToUpload" id="filesToUpload" multiple>
<br><br>
<input type="button" value="Submit" onclick="uploadFiles()">
</div>
</form>
<br>
<br>
<div id="output"></div>
<script>
var rootFolderId = 'xxxxxxxxxxxxxxxxxxx';
var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;
// Upload the files into a folder in drive
// This is set to send them all to one folder (specificed in the .gs file)
function uploadFiles() {
var allFiles = document.getElementById('filesToUpload').files;
var applicantName = document.getElementById('applicantName').value;
if (!applicantName) {
window.alert('Missing applicant name!');
}
var gradesection = document.getElementById('gradesection').value;
if (!gradesection) {
window.alert('Missing Grade & Section!');
}
var folderName = applicantName + ' - ' + gradesection;
if (allFiles.length == 0) {
window.alert('No file selected!');
} else {
numUploads.total = allFiles.length;
google.script.run.withSuccessHandler(function(r) {
// send files after the folder is created...
for (var i = 0; i < allFiles.length; i++) {
// Send each file at a time
uploadFile(allFiles[i], r.folderId);
}
}).createFolder(rootFolderId, folderName);
}
}
function uploadFile(file, folderId) {
var reader = new FileReader();
reader.onload = function(e) {
var content = reader.result;
document.getElementById('output').innerHTML = 'uploading '
+ file.name + '...';
//window.alert('uploading ' + file.name + '...');
google.script.run.withSuccessHandler(onFileUploaded)
.uploadFile(content, file.name, folderId);
}
reader.readAsDataURL(file);
}
function onFileUploaded(r) {
numUploads.done++;
document.getElementById('output').innerHTML = 'uploaded '
+ r.fileName + ' (' + numUploads.done + '/'
+ numUploads.total + ' files).';
if (numUploads.done == numUploads.total) {
document.getElementById('output').innerHTML = 'All of the '
+ numUploads.total + ' files are uploaded';
numUploads.done = 0;
}
}
</script>
The form upload and displays the response to the user.
I want to reset the form so, the form resets to its original state, so when the user upload another file it wont upload the same file again. Right now, the submission message stays and I have no clue on how to reset the form.
I am new to javascript and I have no clue on what to call to rest the form, any idea? TIA Guys :)
As your code snippet only contains input, You can find all inputs using querySelectorAll and reset its value.
Example below. When you click the button it resets all the input.
function resetAllInput() {
const allInput = document.querySelectorAll('input');
allInput.forEach( input => {
input.value = "";
})
}
function uploadFiles() {
console.log('uploading files');
resetAllInput();
console.log('Resetted all inputs');
}
<form id="uploaderForm">
<label for="uploaderForm">Photo Upload Form</label>
<div>
<input type="text" name="applicantName" id="applicantName" placeholder="Your Name">
</div>
<div>
<input type="text" name="gradesection" id="gradesection" placeholder="Your Grade Level & Section">
</div><br>
<div>
You can select multiple Photos upload!<br>
<br>
<input type="file" name="filesToUpload" id="filesToUpload" multiple>
<br><br>
<input type="button" value="Submit" onclick="uploadFiles()">
</div>
</form>
You can assign null value to your input element:
const reset = () => {
let fileInput = document.getElementById('file-input');
fileInput.value = null;
}
<input type="file" id="file-input">
<button onclick="reset()">Reset</button>

How to pass form data to GAS

I am trying to pass data from a form into a Google Apps Script but when I press submit I am greeted by I blank screen.
Form:
<div id="nameDiv">
<form action="https://script.google.com/a/umbc.edu/macros/s/AKfycbztum1ImJZeXXYt0fFhwOAMUsB5zCsJQohrum4W7qiH/dev">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="google.script.run.nameSearch()">
</form>
</div>
Script:
function nameSearch(){
try {
var firstName = document.getElementById("fname").value
var lastName = document.getElementById("lname").value
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15]
}
}
document.getElementById('nameDiv').innerHTML =
"<center>Last Name:" + lastName + "</center>" +
"</br><center>First Name:" + firstName + "</center>"
} catch(e) {
alert(e)
}
}
I am trying to pass this data to the script so that it can use it to search a google sheet so I cannot just place the script in the html as a client side script. Any thought?
All the HTML-related methods (getElementById, innerHTML, etc.) should be in client-side script, and Apps Script methods should be in the server-side.
If I understand you correctly, you want to do the following:
When this form gets submitted, look for the row whose columns K and L match the inputted fields (indexes 10 and 11 from inputData array).
For this row, return data from columns O and P (indexes 14 and 15 from inputData array).
Write this returned data to the HTML.
If all this is correct, then you could do this:
Add an onclick event in the submit input that will fire a client-side function (a function that is declared inside the tags in the HTML). There is no need to use a for this. The HTML body could be something like this:
<div id="nameDiv">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="clientNameSearch()">
</div>
From this client-side function called clientNameSearch(), retrieve the values from fname and lname, and use these as parameters when you call a server-side function called nameSearch):
function clientNameSearch() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
google.script.run.withSuccessHandler(onSuccess).nameSearch(firstName, lastName);
}
This server-side function iterates through all rows with content in the spreadsheet, and returns the result for the first row whose columns K and L match the inputted data:
function nameSearch(firstName, lastName){
try {
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15];
return result;
}
}
} catch(e) {
alert(e)
}
}
This result is then passed as a parameter to a client-side function called onSuccess via a success handler. This is necessary since server-side functions called by google.script.run don't return anything directly, as specified here. Then onSuccess writes the result to the HTML:
function onSuccess(result) {
document.getElementById('nameDiv').innerHTML = "<div>" + result + "</div>";
}
Full code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id="nameDiv">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="clientNameSearch()">
</div>
</body>
<script>
function clientNameSearch() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
google.script.run.withSuccessHandler(onSuccess).nameSearch(firstName, lastName);
}
function onSuccess(result) {
document.getElementById('nameDiv').innerHTML = "<div>" + result + "</div>";
}
</script>
</html>
And the Code.gs would be like:
function nameSearch(firstName, lastName){
try {
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15];
return result;
}
}
} catch(e) {
alert(e)
}
}
function doGet(e) {
return HtmlService.createHtmlOutputFromFile("your-html-name");
}
I'm not sure you want to write the result to the HTML, but in any case, at this point it shouldn't be difficult to modify this so that it writes exactly what you want and where you want.
Reference:
google.script.run.myFunction(...) (any server-side function)
withSuccessHandler(function)
I hope this is of any help.
Try this:
Launch the dialog fill the text boxes and click submit. The view logs and see the next dialog.
function launchADialog() {
var html='<form><br /><input type="text" name="Name" /> Name: <br /><input type="text" name="Age" /> Age: <br />';
html+='<select name="Children" ><option value="0">None</option><option value="1">One</option><option value="2">Two</option></select> Children:<br />';
html+='<input type="button" value="Submit" onClick="google.script.run.processForm(this.parentNode);" /></form>';
var userInterface=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "The Form");
}
function processForm(form) {
Logger.log(JSON.stringify(form));
var s=Utilities.formatString('<br />Name: %s <br />Age:%s <br />Number Of Children: %s', form.Name, form.Age, form.Children);
s+='<br /><input type="button" value="Close" onClick="google.script.host.close();" />';
var userInterface=HtmlService.createHtmlOutput(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "Form Data")
}

Implement shopping cart JavaScript

here what I am trying to do is when a user clicks the + button function should get called, it looks for the cookie shopping_cart. Then it tries to find the JSON with key 'item_qty', which is key-value pair of all the items in the cart. But the cart is not updating, moreover when clicked on + button is showing Unexpected token N in JSON at position 0
In browser console I am getting it as
"csrftoken=some_value; shopping_cart=None"
var updateCart = function (count) {
$('#cart-info').val($('#cart-info').val() + count);
};
var item_add = function (item_slug) {
var shopping_cart = JSON.parse($.cookie("shopping_cart"));
var item_slug = item_slug;
if(shopping_cart.hasOwnProperty('item_qty')){
item_qty_dict = shopping_cart['item_qty'];
if(item_qty_dict.hasOwnProperty(item_slug)){
var count_pre = item_qty_dict[item_slug];
item_qty_dict[item_slug] = count_pre + 1;
}
else {
item_qty_dict[item_slug] = 1;
shopping_cart['item_qty'] = item_qty_dict;
}
}
else {
shopping_cart = {}
shopping_cart['item_qty'] = {item_slug: 1};
}
$.cookie("shopping_cart", JSON.stringify(shopping_cart));
var temp= $.cookie('shopping_cart')
console.log(JSON.parse(temp));
};
var buttonPlus = $(".cart-qty-plus");
var incrementPlus = buttonPlus.click(function () {
var $n = $(this)
.parent(".qnty_chngr")
.find(".qty");
$n.val(Number($n.val()) + 1);
var product_slug = $(this).parent(".qnty_chngr").siblings('.product-slug').val();
console.log(product_slug);
updateCart(1);
item_add(product_slug);
});
HTML:
<div class="qnty_chngr">
<button class="cart-qty-plus" type="button" value="+">+</button>
<input type="text" name="qty" maxlength="12" value="1" class="input-text qty"/>
<button class="cart-qty-minus" type="button" value="-" title="Add less quantity">-</button>
</div>
<input type="hidden" class="product-slug" name="product_slug" value="{{ medicine.slug }}">
<div class="add_to_cart">
<button class="add_to_cart_txt" value="10"><span class="AddInfoBtn">Add </span></button>
</div>,
Seems in your cookie there is no valid JSON. None is not valid, it should be "None" (with quotes). Remove the cookie before testing.
Also if possible try using this library which works the way you expected.
https://github.com/js-cookie/js-cookie

Generating JSON String from Form

I am new to JSON and trying hard to understand it's working.
HTML
<form id="edge" class="form-horizontal" method="post" action="javascript:submit();">
<input type="text" class="input-xlarge" id="latency" name="latency" placeholder="latency">
<input type="text" class="input-xlarge" id="throughput" name="throughput" placeholder="throughput">
<input type="text" class="input-xlarge" id="outUID" name="outUID" placeholder="outUID">
<input type="text" class="input-xlarge" id="inUID" name="inUID" placeholder="inUID">
<button type="submit" class="btn btn-success" >Submit Data</button>
</form>
JSON String to be generated as:
{"latency":1.6,"throughput":6.01,"outUID":{"V_ID":"40"},"inUID":{"V_ID":"16"}}
Here's the form and JSON String to be generated
Could some one guide me how do I create that nested JSON object?
Since it looks like you want the values of outUID and inUID to be nested for some reason you'll need to build the object manually. Here's a simple example:
var $latency = $('#latency'),
$throughput = $('#throughput'),
$outUID = $('#outUID'),
$inUID = $('#inUID');
var myJSONObject = {
latency:$latency.val(),
throughput:$throughput.val(),
outUID:{
V_ID:$outUID.val()
},
inUID:{
V_ID:$inUID.val()
}
};
var stringJSON = JSON.stringify(myJSONObject);
Pure javascript example
var els=document.getElemtById('edge').getElementsByTagName('input');
or
var els=document.querySelectorAll('input[class=input-"xlarge"]');
to get the elements
then
var array=[]
for(var a=0,b;b=els[a]; ++a){
array[a]=b.value
}
array is the json object
JSON.styringify(array)
is the json string
tip: if you plan to use this with ajax
there is a new way called FormData();
so:
var fd=FormData(document.getElemtById('edge'));
contains the whole form , including files
This code allow you to add more fields if required to do so without hard coding the field attributes
http://jsfiddle.net/6vQY9/
HTML
<form id="edge" class="form-horizontal" method="post" action="javascript:submit();">
<input type="text" class="input-xlarge" id="latency" name="latency" placeholder="latency">
<input type="text" class="input-xlarge" id="throughput" name="throughput" placeholder="throughput">
<input type="text" class="input-xlarge" id="outUID" name="outUID" placeholder="outUID" data-prop="V_ID">
<input type="text" class="input-xlarge" id="inUID" name="inUID" placeholder="inUID" data-prop="V_ID">
<button type="submit" class="btn btn-success">Submit Data</button>
</form> <pre></pre>
JS
function submit() {
var JSONString = "";
jQuery('#edge input').each(function () {
var that = jQuery(this);
var val = that.val();
var partJSON = "";
var quote = "\"";
if (that.data('prop')) {
partJSON = "{ " + quote +that.data('prop') + quote+ " : " + quote + val + quote + " }";
} else {
partJSON = val;
}
var comma = that.next('input').length > 0 ? "," : "";
partJSON = quote + that.prop('id') + quote + ":" + partJSON + comma;
JSONString += partJSON
});
JSONString = "{ " + JSONString + " }";
jQuery('pre').text(JSONString);
}

What's the best way to update the input names when dynamically adding them to a form?

I'm trynig to come up with a clean and efficient way of handling form input names when dynamically adding more to the POST array.
For example, if I have the following form:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I then click an 'addmore' button which duplicates that HTML and adds it back into the document. Resulting in:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I'm trying to find the best way to increment that name index so I can use the data on the server. So far, I've been using the following code:
$('.addmore').click(function()
{
var $button = $(this);
var $fieldset = $button.prev('fieldset');
var $newset = $('<div class="new">' + $fieldset[0].innerHTML + '</div>');
$newset.insertBefore($button);
updatenames($newset, $('fieldset').length + 1);
});
function updatenames($set, newIndex)
{
/*
updates input names in the form of
set-index.name
set-index
*/
var findnametype = function(inputname)
{
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') != -1)
{
var data1 = inputname.split('-');
var data2 = data1[1].split('.');
// [type, set, index]
return [1, data1[0], parseInt(data2[0])]
}
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') == -1)
{
var data = inputname.split('-');
return [2, data[0], data[1]];
}
return false;
};
var type = findnametype($set.find('input:eq(0)')[0].name);
$set.find('input, select').each(function()
{
var $input = $(this);
var oldname = $input[0].name;
var newname = false;
switch (type[0])
{
case 1: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
case 2: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
}
$input[0].name = newname;
});
return type;
}
That updatenames function is a variation of what I've been using lately. In this case, I check to find the format of the input name. I then increment the index.
The incrementing, as you've probably noticed, happens in the DOM. As a 'part 2' to my question, I'd like to learn how to have that object returned for me to then insert into the DOM.
Something like:
$newset = updatenames($newset, $('fieldset').length +1);
$newset.insertBefore($button);
Your help is appreciated. Cheers.
Have you considered using array-based field names? You wouldn't have to alter those at all:
<input type="text" name="users.firstname[]" />
<input type="text" name="users.lastname[]" />
whether this works for you will of course depend on what you're going to do with the fields.
<script type="text/javascript">
$(document).ready(function () {
$('.addmore').click(function () {
var fieldset = $(this).prev('fieldset');
var newFieldset = fieldset.clone();
incrementFieldset(newFieldset);
newFieldset.insertBefore($(this));
});
});
function incrementFieldset(set) {
$(set).find('input').each(function () {
var oldName = $(this).attr('name');
var regex = /^(.*)-([0-9]+)\.(.*)$/;
var match = regex.exec(oldName);
var newName = match[1] + '-' + (parseInt(match[2]) + 1) + '.' + match[3];
$(this).attr('name', newName);
});
}
</script>
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
<input type="button" class="addmore" value="Add" />
<fieldset>
<input index=1 var=user prop=firstname />
<input index=1 var=user prop=lastname />
</fieldset>
<fieldset>
<input index=2 var=user prop=firstname />
<input index=2 var=user prop=lastname />
</fieldset>
before you submit your form
get the custom attributes and construct your 'name' attribute
[update]
its jsp but shouldn't be hard for u to convert to php
<%
for (int i = 0; i < 1000; i++) {
%>
<fieldset>
<input index=<%=i%> var=user prop=firstname />
<input index=<%=i%> var=user prop=lastname />
</fieldset>
<%
}
%>
for the js code
$('button').click(function(){
$('input').each(function(i, node){
var $node = $(node);
$node.attr('name', $node.attr('var') + $node.attr('index') + "."+ $node.attr('prop'))
});
});

Categories

Resources