How to validate multidimensional array value in angular 6? - javascript

I have array like the below
data = [
[product, billdetail],
[avn, 200],
[plioc,3000],
[myjio,4000]
]
for(var i = 1; i < data.length; i++) {
var cube = data[i];
for(var j = 0; j < cube.length; j++) {
console.log("cube[" + i + "][" + j + "] = " + cube[j]);
if(cube[j] === "")
{
alert('empty value');
}
}
}
I am doing empty validation here, i also want validation like product should have only alphabets and billdetail should have number only.so how can i achieve that here.please help me for the same.
(consider first row is table header and other rows are values.)

There are many ways to do this, one of is below.
data = [
['product', 'billdetail'],
['avn', 213],
['plioc',3000],
['myjio',4000],
['inval1d produc1', 'invalidbill']
]
for (let i = 1; i < data.length; i++) {
let product = data[i][0];
let bill = data[i][1];
if (!product || !bill) {
console.log('Product or Bill is null', product, bill);
}
if (!product.match(/^[A-Za-z]+$/)){
console.log('Invalid Product:', product);
}
if (typeof(bill) !== 'number') {
console.log('Invalid Bill:', bill);
}
}

Related

JavaScript Grid copy as String

I am having little problem on JavaScript. What I am doing is copying data from a grid and pasting into another. I was able to access the value from the cell, but problem comes as I try to format those value to string.
my code:
var colseperator = '~';
var rowseperator = ' ';
var clipStr = "";
if(selecttype = "area")
{
for (var i = startrow; i <= endrow; i++)
{
for (var j = startcol; j <= endcol; j++)
{
var cellValue = objGrid.getCellValue(i,j);
if(this.gfn_isNull(cellValue))
{
cellValue = "Null";
}
clipStr = clipStr + cellValue;
if(j != endcol)
{
clipStr = clipStr + colseperator;
}
}
if(i != endrow)
{
clipStr = clipStr + rowseperator;
}
}
}
From code above, my intention is copy the data into string format and separate each data with separator(in my case '~' for columns and 'indent' for rows). However, when I select one column(multi rows) and copy it, it would add column separators to all the rows.
I was thinking that if(j != endcol){clipStr = clipStr + colseperator;} would stop it from adding unnecessary separator. Am I doing something wrong here? And any tips on iterating the selected grid cells or formatting string?
example:
When I select those three lines,
row
data
1
a
2
b
3
c
Output:
a~ b~ c~
My expected output:
a b c
You could add a variable for a cols and add the separator if not iteratng the first item.
var colseperator = '~',
rowseperator = ' ',
clipStr = "";
if (selecttype = "area") {
for (var i = startrow; i <= endrow; i++) {
var cols = "";
for (var j = startcol; j <= endcol; j++) {
var cellValue = objGrid.getCellValue(i, j);
if (this.gfn_isNull(cellValue)) cellValue = "Null";
if (j !== startcol) cols += colseperator;
cols += cellValue;
}
if (j !== startcol) clipStr += rowseperator;
clipStr += cols;
}
}

Break if value from range on sheet1 is found in range on sheet2 not working

Basically, the user will input data on a new item on sheet NovoItem. When the Save Button (to be added) is pressed, the code is supposed to check on sheet2 (ArquivoItens) if the item is already there. If so, then it should break.
The code is not breaking if value is found on sheet2 (ArquivoItens):
function copyrange() {
var sourceSheet = 'Novo Item';
var destinationSheet = 'ArquivoItens';
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sourceSheet);
var ActiveUser = Session.getActiveUser();
//it add current user and a timestamp to the last 2 columns on sheet1.
var val = sheet.getRange("Q12:Q")
.getValues();
for (var i = 0; i < val.length; i++) {
if (val[i] > 0) {
sheet.getRange(12, 34, i + 1, 1)
.setValue(new Date());
sheet.getRange(12, 35, i + 1, 1)
.setValue(ActiveUser)
}
}
var LastRowSource = sheet.getLastRow();
var LastColumnSource = sheet.getLastColumn();
var values = sheet.getRange(11,1,LastRowSource,LastColumnSource).getValues();
var csh = ss.getSheetByName(destinationSheet);
var data = [];
for (var i = 1; i < values.length; i++) {
if ( values[i][0] != '') {
data.push(values[i]);
//sheet.deleteRow(i+1)
}
}
var dataNovoItem = sheet.getRange("B12:B").getValues(); // gets data (item number) in the sheet where data is input
var dataArquivoItens = csh.getRange("B2:B").getValues(); //gets the item number on the datawarehouse sheet
for(var n=1; n < dataNovoItem.length ; n++){
for(var j=1; j< dataArquivoItens.length ; j++){
if (dataNovoItem[n] != 0 && dataArquivoItens[j] != 0) {
if(dataNovoItem[n] == dataArquivoItens[j]) {
break;
}
}
}
}
Logger.log("Novo Item" + dataNovoItem);
Logger.log("ArquivoItens" + dataArquivoItens);
//Copy data array to destination sheet
csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data);
}
Here's the log I'm getting:
Any help is appreiated.
You aren't using the iterator to access the index that you're iterating through.
It should be
for(var n=1; n < dataNovoItem.length ; n++){
for(var j=1; j< dataArquivoItens.length ; j++){
if (dataNovoItem[n] != 0 && dataArquivoItens[j] != 0) { // this is where I try to eliminate blank rows in both ranges. I've tried != '', but it gets me the same result on the print below.
if(dataNovoItem[n] == dataArquivoItens[j]) {
break; //not working
}
}
}
}
Logger.log("Novo Item" + dataNovoItem);
Logger.log("ArquivoItens" + dataArquivoItens);
I ended up solving this by iterating only through the existing list and comparing each row with the value I had set on the current sheet. This is probably too logic to yur programmers, but for a beginner like me, this can be a pain.
This is how the working is now:
var newItemID = sheet.getRange("W5").getValue(); //get the destination cell, where the item will be set
var itemIDArquivoItens = csh.getRange(2, 1, csh.getLastRow(),1).getValues(); //gets the data range where the existing ID's to be compared against are
var message = "Item já cadastrado!"; //Message to be displayed in case the ID already exists in the list;
for(j = 1; j < itemIDArquivoItens.length; j++) { //loops through existing ID
if(itemIDArquivoItens[j][0] == newItemID) { //if the ID already exists, pop up a message and stop the code from running
Browser.msgBox(message)
return;
}
}

JavaScript unexplained failure CRM 2013

I have the following applied as a library to a CRM 2013 form
function calcServicePriceTotal() {
alert("Start");//----------HERE
if (document.getElementById("Services")) {
alert("InsideIf"); //----------HERE
var grid = document.getElementById("Services").control;
alert("ThisFar?");//----------HERE
var ids = grid.Control.get_allRecordIds()
alert("ThisFar2?");//----------HERE
for (i = 0; i < ids.length; i++) {
alert("InsideFor");//----------HERE
var cellValue = grid.control.getCellValue('iss_salesprice', ids[i]);
var number = Number(cellValue.replace(/[^0-9\.]+/g, ""));
sum = sum + number;
}
Xrm.Page.data.entity.attributes.get("ava_tempgrossvalue").setValue(sum);
alert("Done");//----------HERE
}
else {
alert("Else");//----------HERE
setTimeout("calcServicePriceTotal();", 2500);
}
}
For some reason I get as far as the alert("ThisFar?") line but then nothing else happens.
Does that mean that there is a problem with var ids = grid.Control.get_allRecordIds()? I don't know why I'm not at least seeing "ThisFar2".
Can anyone see anything obvious?
function calcServicePriceTotal() {
if (document.getElementById("Services")) {
var grid = document.getElementById("Services").control;
var ids = grid.get_allRecordIds()
var sum = 0
for (i = 0; i < ids.length; i++) {
var cellValue = grid.getCellValue('iss_salesprice', ids[i]);
var number = Number(cellValue.replace(/\D/g, ''));
number = number/100;
sum = sum + number;
}
Xrm.Page.data.entity.attributes.get("iss_value").setValue(sum);
}
else {
setTimeout("calcServicePriceTotal();", 1500);
}
}
Final working solution

Simple Quiz Game JavaScript

I'm just learning now. Can you please help me, why am I not getting the correct output. This is my code:
//ask questions
var quiz = [
["When is Bulgaria established?", 681],
["What year was it before 16 years?", 2000],
["When does WWII ends?", 1945]
];
//variables
var answer = [];
var correct = [];
var wrong = [];
var correctAns = 0;
var wrongAns = 0;
var oList = "<ol>";
//function to print the result in ordered list
function printResult(result){
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[i] + "</li>";
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML = message;
}
//looping, adding correct and wrong answeres
for(var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if(parseInt(answer[i]) == quiz[i][1]){
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if(correct.length < 1 || correct == undefined){
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1){
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if(wrongAns > 0){
print(printResult(wrong));
}
}
I have watched this code over and over again and I still can't understand why am I getting undefined as a result. In the debugger, after the loop I check my vars and everything seems ok.
In your printResult function you are using var i instead of j,
Also you better use innerHtml+=message;
//ask questions
var quiz = [
["When is Bulgaria established?", 681],
["What year was it before 16 years?", 2000],
["When does WWII ends?", 1945]
];
//variables
var answer = [];
var correct = [];
var wrong = [];
var correctAns = 0;
var wrongAns = 0;
//function to print the result in ordered list
function printResult(result){
//HERE:
var oList = "<ol>";
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[j] + "</li>";
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML += message;
}
//looping, adding correct and wrong answeres
for(var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if(parseInt(answer[i]) == quiz[i][1]){
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if(correct.length < 1 || correct == undefined){
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1){
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if(wrongAns > 0){
print(printResult(wrong));
}
}
<div id="output">
</div>
Basically you have three problems.
reuse of oList, the variable should be inside declared and used only in printResult.
Inside of printResult, use of i where j have been used and
At print, you replace the actual content with new content.
Just a small hint with variable names for counting. It is good practise to start always with i instead of j and go on with the letters in the alphabet.
var quiz = [["When is Bulgaria established?", 681], ["What year was it before 16 years?", 2000], ["When does WWII ends?", 1945]],
answer = [],
correct = [],
wrong = [],
correctAns = 0,
wrongAns = 0;
//function to print the result in ordered list
function printResult(result) {
var oList = "<ol>"; // !!! move variable inside of the function
for (var j = 0; j < result.length; j++) {
oList += "<li>" + result[j] + "</li>"; // !!! use j indstead if i
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML += message; // !!! append message
}
//looping, adding correct and wrong answeres
for (var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if (parseInt(answer[i]) == quiz[i][1]) {
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if (correct.length < 1 || correct == undefined) {
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1) {
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if (wrongAns > 0) {
print(printResult(wrong));
}
}
Your main mistake is using i intead of j:
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[j] + "</li>";// here was i before
}

Counting # of Times Value Appears in Array In For Loop [Javascript]

Desired:
In class Games, there is a column named RoundWinners that contains arrays filled with multiple UserId. For each Round that a player wins, their UserId is added to the array:
The front-end displays a list displaying each Game in the DB. For each Game, I want to count the number of rounds the current user, currentUserId, has won, and display this number as userScore.
Example:
Current User: Bob
Game 1, Score = 2:
["Bob", "Sue", "Joe", "Bob"]
Game 2, Score = 1:
["Bob", "Lahkim"]
Game 3, Score = 0:
["John", "Mark", "Ronnie", "Alice"]
Code:
var userScore = 0;
var userScores = [];
for (i = 0; i < roundWinners.length; i++) {
if (roundWinners[i] == currentUserId) {
userScore++;
userScores.push(userScore);
};
};
var numberOf = gameIds.length;
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
text += "<div class='GameContainer'> + userScores[i] + </div>";
text += "</li>";
}
text += "</ul>";
//Ammend HTML
document.getElementById("games").innerHTML = text;
Current Error:
The first game displays a userScore of 1, although the current user hasn't won any rounds, and all subsequent games display "undefined".
You have to use 2 for loops for this...
var roundWinners = [["Bob", "Sue", "Joe", "Bob"],["Bob", "Lahkim"],["John", "Mark", "Ronnie", "Alice"]];
var gameIds = [1,2,3];
var currentUserId = "Bob";
var userScore;
var userScores = [];
for (i = 0; i < roundWinners.length; i++) {
userScore = 0;
for (j=0; j < roundWinners[i].length; j++){
if (roundWinners[i][j] == currentUserId) {
userScore++;
}
}
userScores.push(userScore);
}
var numberOf = gameIds.length;
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
text += "<div class='BottomContainer'>" + userScores[i] + "</div>";
text += "</li>";
}
text += "</ul>";
//Ammend HTML
document.getElementById("games").innerHTML = text;
<div id="games"></div>
The reason that you are always getting 1 as the userScore is because you're pushing the userScore into userScore each time you find a match. Instead, you should loop through all the roundWinners, count the number of times the currentUserId appears, and then push to the array of userScores. I have edited your code below with a comment indicating the change.
var userScore = 0;
var userScores = [];
for (i = 0; i < roundWinners.length; i++) {
if (roundWinners[i] == currentUserId) {
userScore++;
};
};
//Push to userScores AFTER you finish going through all of the round winners
userScores.push(userScore);
var numberOf = gameIds.length;
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
text += "<div class='GameContainer'> + userScores[i] + </div>";
text += "</li>";
}
text += "</ul>";
//Ammend HTML
document.getElementById("games").innerHTML = text;

Categories