Hey guys i need some code that will split an array that holds a string which is an item and amount with the delimiter being the (:). (eg. Gas:30 )
loading the elements from the transArray into the values of hmtl texboxes for the item and amount fields
Please don't be to harsh with the comments this is my first language for a type-language.
Any help is appreciated!
var load = function ()
{
mySetArray(); //Fills the transArray randomly with 1-4 items
var item = '';
var amount = '';
for ( i=1; i<=transArray.length; i++)
{
item = 'item' + i;
amount = 'amount' + i;
transArray.split(":");
}
}
var mySetArray = function ()
{
var myRandom = Math.floor((Math.random() * 100) / 25) + 1; //a number between 1 and 4
transArray = new Array(); //Resets the Array to empty
if (myRandom == 1)
{
transArray[0] = "Food:200";
}
if (myRandom == 2)
{
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
}
if (myRandom == 3)
{
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
transArray[2] = "Mortgage:1800";
}
if (myRandom == 4)
{
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
transArray[2] = "Mortgage:1800";
transArray[3] = "Cable:130";
}
}
window.onload = function ()
{
$("load").onclick = load;
}
To split an array, such as:
transArray[0] = "Food:200";
Just use split:
var newArray = transArray[0].split(':');
// newArray[0] = 'Food', newArray[1] = '200'
change:
for ( i=1; i<=transArray.length; i++) {
item = 'item' + i;
amount = 'amount' + i;
transArray.split(":");
}
to
for ( i=1; i<=transArray.length; i++) {
item = 'item' + i;
amount = 'amount' + i;
var splitted = transArray[i].split(":"); <-- split each item in transArray
console.log(splitted);
}
Here transArray is an array. You should use split on it's values i.e transArray[i].split(":");
So update your code like this :
for ( i=1; i<=transArray.length; i++)
{
item = 'item' + i;
amount = 'amount' + i;
var splittedData = transArray[i].split(":");
// It will give Item in 0th index and amount in 1st field.
}
var arr = new Array();
arr[0] = "Gas:200";
var newArr = arr[0].split(':');
JSFIDDLE DEMO
Call load function where ever you want or as it is (as i have done)
function load()
{
transArray = mySetArray(); //Fills the transArray randomly with 1-4 items
var item = '';
var amount = '';
for ( i=0; i<=transArray.length; i++)
{
ar = transArray[i].split(":");
alert((i+1)+" Item="+ar[0] + " Amount="+ ar[1]); // You ca use it in your own way
}
}
load();
function mySetArray()
{
var myRandom = Math.floor((Math.random() * 100) / 25) + 1; //a number between 1 and 4
transArray = new Array(); //Resets the Array to empty
if (myRandom == 1)
{
transArray.push("Food:200");
}
if (myRandom == 2)
{
transArray.push("Food:200");
transArray.push("Toys:700");
}
if (myRandom == 3)
{
transArray.push("Food:200");
transArray.push("Toys:700");
transArray.push("Mortgage:1800");
}
if (myRandom == 4)
{
transArray.push("Food:200");
transArray.push("Toys:700");
transArray.push("Mortgage:1800");
transArray.push("Cable:130");
}
return transArray;
}
Related
Here is my code:
var ct = 0;
var sheet = SpreadsheetApp.getActiveSheet();
var cell = sheet.getCurrentCell();
var cellcol = cell.getColumn();
var cellrow = cell.getRow()
var notate = cell.getA1Notation();
var temp, letter = '';
var solved = new Array()
var pend = new Array()
var cellcol1 = cellcol + 1;
var p;
function copycell1() {
getFirstEmptyRowByColumnArray();
cell.copyTo(sheet.getRange(ct,cellcol,1,1))
cell.clearContent();
}
function getFirstEmptyRowByColumnArray() {
columnToLetter(cellcol)
var column = sheet.getRange(letter + ':' + letter);
var values = column.getValues();
while ( values[ct] && values[ct][0] !== "" ) {
ct++;
}
ct++
}
function getFirstEmptyRowByColumnArray2() {
columnToLetter(cellcol);
var cellrow = cell.getRow();
var column = sheet.getRange(letter + cellrow + ':' + letter);
var values = column.getValues();
while ( values[ct] && values[ct][0] !== "" ) {
ct++;
}
}
function columnToLetter(column)
{
while (column > 0)
{
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
}
return letter;
}
function totalSolved() {
getFirstEmptyRowByColumnArray2()
var compacolumn = sheet.getRange(letter + cellrow + ':' + letter + (ct+cellrow));
var valuesSolved = compacolumn.getValues();
solved = valuesSolved
}
function totalPending() {
letter = '';
ct = 0;
cellcol = cellcol + 1;
getFirstEmptyRowByColumnArray2()
cellrow = cell.getRow();
var compacolumn = sheet.getRange(letter + cellrow + ':' + letter + (ct + cellrow));
var valuesPend = compacolumn.getValues();
pend = valuesPend
}
function compa() {
var i;
var o;
totalSolved();
totalPending();
for ( i = 0; i < pend.length; i++ ) {
for (o = 0; o < solved.length; o++) {
if (pend[i].toString() == solved[o].toString()) {
sheet.getRange(i+cellrow,cellcol1).clearContent();
}
else {
}
}
}
clearemp();
clearemp();
clearemp();
}
function clearemp() {
lastRowForColumn(cellcol1)
for (var i = 0; i < p; i++){
if((sheet.getRange(letter+(cellrow+i)).getValue()) == "")
{
Logger.log(sheet.getRange(letter+(cellrow+i)).getA1Notation());
sheet.getRange(letter+(cellrow+i)).deleteCells(SpreadsheetApp.Dimension.ROWS);
}
}
}
function lastRowForColumn(column){
var numRows = sheet.getLastRow();
Logger.log("numRows is " + numRows)
var data = sheet.getRange(1, column, numRows).getValues();
Logger.log("data is " + data)
Logger.log("data.length is " + data.length)
for(p = data.length - 1 ; p >= 0 ; p--){
if (data[p][0] != null && data[p][0] != ""){
Logger.log ("p is " + p)
return p + 1;
}
}
}
function test() {
Logger.log("cellcol is " + cellcol1)
lastRowForColumn(cellcol1)
Logger.log("p is " + p)
}
The function I'm talking about is compa().
The specific function that deletes the cells is clearemp(). But whenever I do it it is still not complete and I am at a loss on what to do
CONTEXT: I am working on comparing two lists and then removing the equal cells on the 2nd column and then shifting the cells up.
function delcels(col=1) {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('Sheet1');
const rg=sh.getRange(1,col,sh.getLastRow());
const c1=rg.getValues().filter((e)=>!(e===""));//thanks to iansedano
rg.clearContent();
sh.getRange(1,col,c1.length,1).setValues(c1);
}
A possible solution
There are a few approaches, but here is one, that is essentially the same as Cooper's, except that it doesn't clear values that are 0. Only if the cell is empty, i.e. "" will it clear the cell.
/**
* Clears empty cells in column
*
* #param columnToClear - the column that should be cleared, defaults to 1
* #param sheetName - the name of the sheet, defaults to "Sheet1"
*/
function clearBlanks(columnToClear = 1, sheetName = "Sheet1") {
const file = SpreadsheetApp.getActive();
const sheet = file.getSheetByName(sheetName);
const range = sheet.getRange(1, columnToClear, sheet.getLastRow(), 1);
const output = range.getValues().filter(e => !(e[0] === ""));
range.clearContent();
const outputRange = sheet.getRange(1, columnToClear, output.length, 1)
outputRange.setValues(output)
}
This gets the whole range into memory as a 2D array.
Uses filter to take out any values that are strictly equal === to and empty string. So it will not clear 0 values.
Clears the whole column, and pastes in the filtered array.
Filter
This is called on an array
array.filter(function)
You need to pass in a function that will return either a True or False value. The filter will go through each element and if it gets False then it will remove that element. In the example above, its passed in as an arrow function. When its an arrow function, if its on one line, you don't need to include the return statement.
There are a few useful functions that are like this. For example, forEach and map that can be very useful for the types of operation you are doing.
Reference
filter
I've created a script to create a new array called spots, here is the script:
main();
function main() {
var doc = app.activeDocument;
var selectedSwatches = doc.swatches.getSelected();
var pageNumber = 1;
var count = 0;
if (selectedSwatches.length > 0) {
var text = 'var spots = new Array(\n';
for (var i = 0; i < selectedSwatches.length; i++) {
var swatch = selectedSwatches[i]
var color = swatch.color;
// Spot
if (color.typename == "SpotColor") {
count++;
text += '"' + color.spot.name + '", ' + "\n";
color = color.spot.color;
if (count % 10 == 0)
pageNumber++;
}
}
var textend = ');';
var textArray = text + textend;
alert(textArray);
} else {
alert("No Swatches Selected.");
}
}
This script alerts the following:
var spots = new Array(
"Yellow 012 C",
"Bright Red C",
);
How do I now alert the contents of that array i.e. Yellow 012 C, Bright Red C
I have tried using:
alert(spots);
But I get the error undefined maybe because the array is created on the fly and its not placed in the script?
UPDATE:
As per the comments, I have edited the script adding:
var spots = [];
spots.push(color.spot)
alert(spots);
I now get the following error: undefined is not an object
Here's the full script
main();
function main() {
var doc = app.activeDocument;
var selectedSwatches = doc.swatches.getSelected();
var pageNumber = 1;
var count = 0;
if (selectedSwatches.length > 0) {
var text = 'var spots = new Array(\n';
for (var i = 0; i < selectedSwatches.length; i++) {
var swatch = selectedSwatches[i]
var color = swatch.color;
// Spot
if (color.typename == "SpotColor") {
count++;
text += '"' + color.spot.name + '", ' + "\n";
color = color.spot.color;
if (count % 10 == 0)
pageNumber++;
}
}
var textend = ');';
var textArray = text + textend;
var spots = [];
spots.push(color.spot)
alert(spots);
} else {
alert("No Swatches Selected.");
}
}
Try
function main() {
//var doc = app.activeDocument;
var selectedSwatches
= [{"color":{"spot":{"color":"#ff0000","name":"red"},"typename":"SpotColor"}}
,{"color":{"spot":{"color":"#000000","name":"black"},"typename":"SpotColor"}}];
// = doc.swatches.getSelected();
var pageNumber = 1;
var count = 0;
var spots = [];
if (selectedSwatches.length > 0) {
for (var i = 0; i < selectedSwatches.length; i++) {
var swatch = selectedSwatches[i]
var color = swatch.color;
// Spot
if (color.typename == "SpotColor") {
count++;
spots.push(color.spot.name);
color = color.spot.color;
if (count % 10 == 0)
pageNumber++;
}
}
alert(spots.toString());
} else {
alert("No Swatches Selected.");
}
}
<button onclick="main()">Main</>
I am trying to take user input in form of a lot of strings. I want to store them in an array, and the input should be seperated by line breaks.
It should be very much like this: https://www.random.org/lists/
I can not grasp where to being - can someone help? I am using JavaScript but any solutions using JS or jQuery would be great!
I have posted my JS. I want the var people from user input, instead of having to populate the array myself.
Thanks,
$(document).ready(function() {
$(".btn").on('click', function() {
var people = ["Markus Eriksson", "Leticia Hoshino", "Yemi Afolabi", "Eskil Fogelström", "Josefina Liedberg", "David Bjørn Bograd", "Tilda Dahlgren", "Damien Vignol", "Sofie Cousu", "Carolina Lindelöw", "Bilal Khan", "Louise Brandrup-Wognsen", "Emilia Lehto", "Albin Hagström",
"Victor Borg", "Anna Stella Lo-Ré", "Loucmane", "Angelica Ruth", "Victoria VL", "Johan Hellström", "Micke Skoglund", "Anna Unger", "Isaac Sennerholt", "Cyndie Léa Vintilescu", "Mahle Rakela Robin", "Louise Ek", "Ibrahim Bajwa", "Abodi Ismail",
"Alex Ashman", "Elin Grass Casalini", "Amanda Schultz", "Abenezer Abebe", "Julia Hoff", "Enny Hellsén", "Michel George", "Abdullahi Hussein", "Teodor Meurling", "Andrea Sami Mogren", "Thea Arpine Gasparyan", "Jakob Eberson"
];
var groupSize = $("input[name=checkListItem]").val();
var groups = [];
$(".group").remove();
// Randomizing function
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
};
people.shuffle();
// Split people into chunks and push new arrays into var groups
while (people.length > 0) {
chunks = people.splice(0, groupSize);
var chunksSpace = chunks.join(', ');
groups.push(chunksSpace);
}
// Append the groups into the DOM
$(document).ready(function() {
for (var i = 0; i < groups.length; i++) {
$('.all-groups').append("<div class='group'><p><span class='groupheader'>Group " + (i + 1) + "</span></br> " + groups[i] + "</p></div>");
}
});
});
});
Pure Javascript
document.getElementById("element_id").value.split("\n");
OR JQuery $("#element_id").val().split("\n");
For your example give your input id='people' and should work, also avoid extra line breaks by .replace(/\n+/g,"\n").
$(document).ready(function() {
// Randomizing function
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
};
$(".btn").on('click', function() {
var people = $("#people").val().replace(/\n+/g,"\n").split("\n");
var groupSize = $("input[name=checkListItem]").val();
var groups = [];
$(".group").remove();
people.shuffle();
// Split people into chunks and push new arrays into var groups
while (people.length > 0) {
chunks = people.splice(0, groupSize);
var chunksSpace = chunks.join(', ');
groups.push(chunksSpace);
}
// Append the groups into the DOM
$(document).ready(function() {
for (var i = 0; i < groups.length; i++) {
$('.all-groups').append("<div class='group'><p><span class='groupheader'>Group " + (i + 1) + "</span></br> " + groups[i] + "</p></div>");
}
});
});
});
var text = $('#total-number').text();
var eachLine = text.split('\n');
alert('Lines found: ' + eachLine.length);
for(var i = 0, l = eachLine.length; i < l; i++) {
alert('Line ' + (i+1) + ': ' + eachLine[i]);
}
Use split to split a multi line string into parts:
var textarea = document.querySelector("textarea");
textarea.addEventListener("change", function(e) {
console.log(textarea.value.split((/[\n\r]/g)));
});
<textarea></textarea>
Regex links:
\r
\n
I have the below code which checks my dynamically produced offhire boxes to see if there is an integer value present onsubmit. If i were to check the sum of the array at the end to see if all boxes added together was bigger than 0 how would i accomplish that.
function validateoffhire(form) {
var num1 = document.getElementById('num1');
var test2Regex = /^[0-9 ]*$/;
var num2 = num1.value;
var i=0;
var offhire1 = [];
for(var i = 0; i < num2; i++) {
offhire1[i] = document.getElementById('offhire1' + i);
var offhire2 = offhire1[i].value;
//if(nameRegex.match(pro[i].value)){
if(!offhire2.match(test2Regex)){
//alert("You entered: " + pro[i].value)
inlineMsg('offhire1' + i,'This needs to be an integer',10);
return false;
}
}
return true;
}
many thanks for any help
steve
Change your code by adding an accumulator inside your loop, then check the accumulator outside the loop:
function validateoffhire(form) {
var num1 = document.getElementById('num1');
var test2Regex = /^[0-9 ]*$/;
var num2 = num1.value;
var accumulator = 0;
var i=0;
var offhire1 = [];
for(var i = 0; i < num2; i++) {
offhire1[i] = document.getElementById('offhire1' + i);
var offhire2 = offhire1[i].value;
//if(nameRegex.match(pro[i].value)){
if(!offhire2.match(test2Regex)){
inlineMsg('offhire1' + i,'This needs to be an integer',10);
return false;
}
else{
accumulator += parseInt(offhire2);
}
}
if(accumulator > 0){
return true;
}
}
You are saving all the values in an array. so u can add up all the values using a loop.
var totalValue = 0;
var i=0;
while(offhire1[i])
{
totalValue += offhire1[i] ;
i++
}
if(totalValue)
{
// Non zero
}
Could you be please be more specific if im wrong.
You have to:
Convert input values to a Number
Use the forEach function of an Array to add the values together.
Like:
function validateoffhire(form) {
var num1 = document.getElementById('num1');
var test2Regex = /^[0-9 ]*$/;
var num2 = num1.value;
var i=0;
var offhire1 = [];
for(var i = 0; i < num2; i++) {
offhire1[i] = parseFloat(document.getElementById('offhire1' + i));
var offhire2 = offhire1[i].value;
//if(nameRegex.match(pro[i].value)){
if(!offhire2.match(test2Regex)){
//alert("You entered: " + pro[i].value)
inlineMsg('offhire1' + i,'This needs to be an integer',10);
return false;
}
}
var sum = 0;
offhire1.forEach(function(a) {sum+=a});
// here, sum is the sum of offhire1's values
return true;
}
Is there a way for the JQGrid to return an array of column Data for using multiSelect as opposed to just an array of rowIds ?
At the moment I can only return the last column data that was selected.
jQuery("#buttonSelected").click(function() {
var ids = jQuery("#relatedSearchGrid").getGridParam('selarrrow');
var count = ids.length;
for (var i = 0; i < count; i++) {
var columnData = $("#relatedSearchGrid").find("tbody")[0].rows[$("#relatedSearchGrid").getGridParam('selrow') - 1].cells[1].innerHTML;
alert("In the loop and " + columnData );
}
if (count == 0) return;
var posturl = '<%= ResolveUrl("~") %>Rel******/AddSelected****/' + ids;
if (confirm("Add these " + count + " Docs?")) {
$.post(posturl,
{ ids: columnData },
function() { jQuery("#relatedSearchGrid").trigger("reloadGrid") },
"json");
}
})
Use getRowData to get the data for each row:
var rowData = $("#relatedSearchGrid").getRowData(ids[i]);
var colData = rowData.Name_Of_Your_Column;
var userListjqGrid = $('#UserListGrid'),
selRowId = userListjqGrid.jqGrid('getGridParam', 'selrow'),
userId = userListjqGrid.jqGrid('getCell', selRowId, 'UserId'),
userName = userListjqGrid.jqGrid('getCell', selRowId, 'UserName'),
subIds = $(subgridTableId).getGridParam('selarrrow'),
accessRuleIds = [];
for (var i = 0; i < subIds.length; i++) {
accessRuleIds[i] = $(subgridTableId).getRowData(subIds[i]).AccessRuleId;
}