I want to get this (four keys & values in one object):
[{"sms":"Y","email":"Y","phone":"Y","oto":"Y"},{"sms":"N","email":"N","phone":"N","oto":"N"}]
but this is result :
[{"sms":"Y"},{"email":"Y"},{"phone":"Y"},{"oto":"Y"},{"sms":"N"},{"email":"N"},{"phone":"N"},{"oto":"N"}]
here is my code:
var chkObj = {};
var chkArray = [];
var cntchk = 1;
$("tbody input").each(function(idx){
var Nm = $(this).attr("name");
this.checked ? chkObj[Nm] = 'Y' : chkObj[Nm] = 'N';
cntchk++;
if(cntchk = 4){
chkArray.push(chkObj);
chkObj = {};
cntchk = 1;
}
});
Can you please show us the form as well? This gives a limited scope to answer.
But If i guess right, you have a form wherein you have the following fields sms, email, phone, and then oto, right?
So what you have to do is, instead of doing it for each input, you have to do it once for the four inputs.
Meaning that you have to set chkObj['sms'], chkObj['email'], chkObj['phone'], and then chkObj['oto'] and then do chkArray.push(chkObj).
You missed the second equals sign in this expression:
if(cntchk = 4){, so instead of comparison there is an assignment. Change this to if(cntchk == 4){
You have missed one "=" sign in if condition.
try this:
var chkObj = {};
var chkArray = [];
var cntchk = 1;
$("tbody input").each(function(idx){
var Nm = $(this).attr("name");
this.checked ? chkObj[Nm] = 'Y' : chkObj[Nm] = 'N';
cntchk++;
if(cntchk **==** 4){
chkArray.push(chkObj);
chkObj = {};
cntchk = 1;
}
});
Related
The "Options" should all create a Data Validation dropdown based off of the "Category" input. ManualAutomatic and Option A work fine and return correct dropdowns. Options B thru E return a Data Validation dropdown that contains only "Undefined"
I am new to google scripting. I started with Learn Google Spreadsheet's tutorial and built from there. I apologize in advance if I am asking a question that is answered elsewhere.
var mainWsName = "Bid Sheet";
var nameData = "Data";
var Category = 1;
var ManualAutomatic = 2;
var OptionA = 3;
var OptionB = 4;
var OptionC = 5;
var OptionD = 6;
var OptionE = 7;
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mainWsName);
var wsData = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(nameData);
var manAutoOption = wsData.getRange(2, 1,wsData.getLastRow()-1,3).getValues();
function onEdit(e){
var activeCell = e.range;
var val = activeCell.getValue();
var r = activeCell.getRow();
var c = activeCell.getColumn();
var wsName = activeCell.getSheet().getName();
if (wsName === mainWsName && c === Category && r > 3){
OptionsValidation (val,r);
} else if(wsName === mainWsName && c === ManualAutomatic && r > 3){
NothingScriptRemove (val,r);
}//NothingScriptRemove is useless find a way to remove without breaking
}//end onEdit
function OptionsValidation (val,r){
if(val === ""){
ws.getRange(r,ManualAutomatic).clearContent();
ws.getRange(r,ManualAutomatic).clearDataValidations();
ws.getRange(r,OptionA).clearContent();
ws.getRange(r,OptionA).clearDataValidations();
ws.getRange(r,OptionB).clearContent();
ws.getRange(r,OptionB).clearDataValidations();
ws.getRange(r,OptionC).clearContent();
ws.getRange(r,OptionC).clearDataValidations();
ws.getRange(r,OptionD).clearContent();
ws.getRange(r,OptionD).clearDataValidations();
ws.getRange(r,OptionE).clearContent();
ws.getRange(r,OptionE).clearDataValidations();
} else {
ws.getRange(r,ManualAutomatic).clearContent();
ws.getRange(r,OptionA).clearContent();
ws.getRange(r,OptionB).clearContent();
ws.getRange(r,OptionC).clearContent();
ws.getRange(r,OptionD).clearContent();
ws.getRange(r,OptionE).clearContent();
var filterOptions = manAutoOption.filter(function(o){ return o[0] === val });
var listToApply = filterOptions.map(function (o) { return o[1] });
var cell = ws.getRange(r,ManualAutomatic);
applyValidationtoCell(listToApply,cell);
var firstLevelColValue = ws.getRange(r, Category).getValue();
var filterOptions = manAutoOption.filter(function(o){ return o[0] === firstLevelColValue});
var listToApplyA = filterOptions.map(function (o) { return o[2] });
var cell = ws.getRange(r,OptionA);
applyValidationtoCell(listToApplyA,cell);
var listToApplyB = filterOptions.map(function (o) { return o[3] });
var cell = ws.getRange(r,OptionB);
applyValidationtoCell(listToApplyB,cell);
var listToApplyC = filterOptions.map(function (o) { return o[4] });
var cell = ws.getRange(r,OptionC);
applyValidationtoCell(listToApplyC,cell);
var listToApplyD = filterOptions.map(function (o) { return o[5] });
var cell = ws.getRange(r,OptionD);
applyValidationtoCell(listToApplyD,cell);
var listToApplyE = filterOptions.map(function (o) { return o[6] });
var cell = ws.getRange(r,OptionE);
applyValidationtoCell(listToApplyE,cell);
So I found the answer. A good night's sleep and a clear head make all the difference.
For anyone who stumbles on this looking for answers to similar issues...
This variable isn't pulling the correct data. Or more specifically it isn't pulling the right number of columns.
var manAutoOption = wsData.getRange(2, 1,wsData.getLastRow()-1,3).getValues();
"wsData.getLastRow()-1,3)" The last number is the number of columns that get pulled. Change that number to the number of columns you need to reference and everything else works great.
I need to retrieve variables from an URL.
I use this found function:
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
return obj;
}
var urlexample = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
The output is:
{"idPagamenti":["26","27"],"idCliente":["9"]}
But idCliente is always NOT an array, so i'd like to retrieve:
{"idPagamenti":["26","27"],"idCliente": 9 }
This is the fiddle example
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
return obj;
}
var stringa = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
$(document).ready(function(){
alert("testing");
console.log(me);
$(".a").html(JSON.stringify(me));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
</div>
Someone can help me to modify code?
I think your facing a real paradigm problem. Why idCliente wouldn't be an array but idPagamenti would be. You should have all array or none but not both. getParams() function can make this choice for you and you should probably change the way you are working with this.
Anyway, here is a getParams() function that replace any single-valued array to a value. Note that if you have only one idPagamenti in your URI, you will also have a single value for idPagamenti instead of an array.
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
Object.keys(obj).forEach(key => {
if (obj[key].length === 1) {
obj[key] = obj[key][0];
}
})
return obj;
}
var urlexample = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
If you know that you will always get ids as parameters, you can also add a parseInt() for each parameter by replacing var value = spl[1]; with var value = parseInt(spl[1], 10);
I have this simple div:
<div id='names'>
name1[John]
name2[Blake]
name3[Sven]
name4[Ellis]
</div>
And I want to return these variables using JavaScript
var name1 = "John";
var name2 = "Blake";
var name3 = "Sven";
var name4 = "Ellis";
Your question lacks a lot of detail. Can there be more than those four names? Can't you restructure your code to get an easier access to the data?
var toParse = document.getElementById('names').innerHTML;
var m;
var re = /\[(.*)\]/g;
while (m = re.exec(toParse)) {
console.log(m[1]);
}
(https://jsfiddle.net/hL4bu5j1/)
This code looks for text in [Bracers] and outputs it to the console to give you an idea how you could approach this. You should be good to go with that. Wanted to put this as a comment but I'm not yet allowed to.
This should do it:
//document.body.innerHTML = "<div id='names'>\n name1[John]\n name2[Blake]\n name3[Sven]\n name4[Ellis]\n</div";
var obj = {};
var str = document.getElementById("names").innerHTML;
while(str.lastIndexOf(' ') >= 0) {
str=str.replace(' ','')
}
var str=str.split("\n");
for(var i = 0;i<str.length;i++){
if(str[i].length > 2) {
obj[str[i].replace(']','').split('[')[0]] = str[i].replace(']','').split('[')[1];
}
}
console.log(obj)
Here an ugly version :
var divContent = document.getElementById('names').innerHTML;
var array = divContent.trim().split(" ").filter(removeEmpty);
console.log(array)
var name1 = array[0].split('1')[1];
I think Regex suits better for your issue
https://jsfiddle.net/hrgk2s1u/
I'm doing a cart and I want to increment the qty if the item_id exising in localStorage.
<button data-item_id="1" data-item_name="cake" data-item_price="2 dollar">Add to cart</button>
Not sure why my below code doesn't work, it added a new object instead of increment the qty value.
$(function(){
$('button').click(function(){
var item_id = $(this).attr('data-item_id');
var item_name = $(this).attr('data-item_name');
var item_price = $(this).attr('data-item_price');
var arr = JSON.parse(localStorage.getItem('cart')) || [];
var obj = {};
if(arr.length === 0){ // first time insert
obj.item_id = item_id;
obj.item_name = item_name;
obj.item_price = item_price;
obj.item_qty = 1;
}else{
$(arr,function(i){
//doesn't work here
obj.item_qty[i] = parseInt(this.qty) + 1;
});
}
arr.push(obj);
localStorage.setItem('cart',JSON.stringify(arr));
});
});
debug for few hours couldn't solved.
Use {} instead of [] making the arr contain one object per item_id and each object will get 1 added to the qty each time it is called. There is no remove in this code
$(function(){
$('button').on("click",function(e){
var item_id = $(this).data("item_id");
var item_name = $(this).data("item_name");
var item_price = $(this).data("item_price");
var cart = JSON.parse(localStorage.getItem('cart')) || {};
var currentObj = cart[item_id];
if(currentObj){
currentObj.qty++; // increase the qty by one
}
else { // item_id had not been stored before, create it
cart[item_id]= {
"item_name" :item_name,
"item_price":item_price,
"item_qty" :1
}
}
localStorage.setItem('cart',JSON.stringify(cart));
});
});
Then you have to do like this:
$(function(){
$('button').click(function(){
var item_id = $(this).attr('data-item_id');
var item_name = $(this).attr('data-item_name');
var item_price = $(this).attr('data-item_price');
var arr = JSON.parse(localStorage.getItem('cart')) || [];
var obj = {};
obj.item_id = item_id;
obj.item_name = item_name;
obj.item_price = item_price;
obj.item_qty = 1;
detectchange = 'no';
$.each(arr,function(i){
if(this.item_id == obj.item_id){
this.item_qty = parseInt(this.item_qty) + 1; detectchange = 'yes'; }
});
if(detectchange =='no'){
arr.push(obj); }
localStorage.setItem('cart',JSON.stringify(arr));
});
});
In Google App Scripts (GAS), I want to be able to add and remove TextBox and TextArea elements to a FlexTable (that's being used as a form) and not worry about how many there are. I've named the text elements based on a counter to make this process easier.
So, is there a way to get the number of inputs (TextBox + TextArea) passed to e.parameter after the form is submitted?
Here's the relevant code from the FlexTable:
function doGet() {
var app = UiApp.createApplication();
var flex = app.createFlexTable().setId('myFlex');
var counter = 0;
var row_counter = 0;
...
var firstnameLabel = app.createLabel('Your FIRST Name');
var firstnameTextBox = app.createTextBox().setWidth(sm_width).setName('input' + counter).setText(data[counter]);
flex.setWidget(row_counter, 1, firstnameLabel);
flex.setWidget(row_counter, 2, firstnameTextBox);
row_counter++;
counter++;
var lastnameLabel = app.createLabel('Your LAST Name');
var lastnameTextBox = app.createTextBox().setWidth(sm_width).setName('input' + counter).setText(data[counter]);
flex.setWidget(row_counter, 1, lastnameLabel);
flex.setWidget(row_counter, 2, lastnameTextBox);
row_counter++;
counter++;
...
var submitButton = app.createButton('Submit Proposal');
flex.setWidget(row_counter, 2, submitButton);
var handler = app.createServerClickHandler('saveProposal');
handler.addCallbackElement(flex);
submitButton.addClickHandler(handler);
var scroll = app.createScrollPanel().setSize('100%', '100%');
scroll.add(flex);
app.add(scroll);
return app;
}
And here's the code for the ClickHandler (notice that I currently have 39 elements in my FlexTable):
function saveProposal(e){
var app = UiApp.getActiveApplication();
var userData = [];
var counter = 39;
for(var i = 0; i < counter; i++) {
var input_name = 'input' + i;
userData[i] = e.parameter[input_name];
}
So, is there a way to get the number of elements (in this case 39) without manually counting them and assigning this value to a variable?
I'm new at this stuff and I'd appreciate your help.
Cheers!
The simplest way is to add a hidden widget in your doGet() function that will hold the counter value like this :
var hidden = app.createHidden('counterValue',counter);// don't forget to add this widget as a callBackElement to your handler variable (handler.addCallBackElement(hidden))
then in the handler function simply use
var counter = Number(e.parameter.counterValue);// because the returned value is actually a string, as almost any other widget...
If you want to see this value while debugging you can replace it momentarily with a textBox...
You can search for arguments array based object.
function foo(x) {
console.log(arguments.length); // This will print 7.
}
foo(1,2,3,4,5,6,7) // Sending 7 parameters to function.
You could use a while loop.
var i = 0;
var userData = [];
while (e.parameter['input' + i] != undefined) {
userData[i] = e.parameter['input' + i];
i++;
};
OR:
var i = 0;
var userData = [];
var input_name = 'input0';
while (e.parameter[input_name] != undefined) {
userData[i] = e.parameter[input_name];
i++;
input_name = 'input' + i;
};