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;
}
Related
I've been working on a Math Parser project. I'm almost finished but I encountered a problem that I couldn't find the reason for it.
I've got 3 javascript files:
main.js
var button1 = document.getElementById("button");
var text1 = document.getElementById("text");
var output = document.getElementById("result");
button1.addEventListener("click", function(){
var textInput = text1.value;
var cleared = new clearingUnwantedCharacters(textInput);
var marked = new subgroupMarking(cleared.output);
var prioritizedList = new subgroupPrioritization(marked.parenGroups);
for(var i = 0; i <= 360; i++){
var splittedPieces = new splittingOperators(prioritizedList.prioritizedGroups);
var calculatedPieces = new calculatePieces(splittedPieces.seperatedPieces, i, true);
console.log(calculatedPieces.result);
}
});
objects.js
function clearingUnwantedCharacters(inputText){
this.output = inputText;
this.output = this.output.replace(/\s+/g, '');
this.output = this.output.toLowerCase();
}
function subgroupMarking(inputText){
this.parenGroups = [inputText];
this.locLeftParen = markChar(this.parenGroups[0], "(");
this.locRigthParen = markChar(this.parenGroups[0], ")");
for(var i = this.locLeftParen.length-1; i >= 0; i--){
var leftParen = this.locLeftParen[i];
var rightParen = this.locRigthParen.find(function(res){return res > leftParen});
this.parenGroups[i+1] = this.parenGroups[0].substring(leftParen+1, rightParen);
this.parenGroups[0] = changeAt(this.parenGroups[0], leftParen, rightParen+1, "{_"+(i+1)+"}");
this.locLeftParen = markChar(this.parenGroups[0], "(");
this.locRigthParen = markChar(this.parenGroups[0], ")");
}
}
function subgroupPrioritization(subgroupList){
var withParenGroup = [];
var withoutParenGroup = [];
for(var i = 0; i < subgroupList.length; i++){
var content = subgroupList[i].toString();
var hasParenGroup = content.search(/{_\d+}/g);
if(hasParenGroup == -1){
withoutParenGroup.push(content);
}else{
withParenGroup.push(content);
}
}
this.prioritizedGroups = withParenGroup.concat(withoutParenGroup);
}
function splittingOperators(prioritizedGroupList){
this.seperatedPieces = [];
for(var i = prioritizedGroupList.length-1; i >= 0; i--){
var pieces = prioritizedGroupList[i].split(/(\+|\*|\/|\^|\b(?=-)|(?<=})(?=-))/g);
for(var k = 0; k < pieces.length; k++){
if(pieces[k] == ""){
pieces[k] = "+";
}
}
this.seperatedPieces.unshift(pieces);
}
}
function calculatePieces(pieceList, x, degreeOption){
this.result = pieceList;
for(var i = this.result.length-1; i >= 0; i--){ // ["34", "+", "2{_2}"]
for(var k = 0; k < this.result[i].length; k++){ // 34, +, 2{_2}
var specialFlag = false;
var totalMultiplication = (countChar(this.result[i][k], "-")%2 == 0) ? 1 : -1;
var has = {
x : this.result[i][k].includes("x"),
subgroup : (this.result[i][k].search(/{_\d+}/g) != -1),
logarithm : this.result[i][k].includes("log"),
trigonometry : (this.result[i][k].includes("sin") || this.result[i][k].includes("cos") || this.result[i][k].includes("tan") || this.result[i][k].includes("cot"))
};
if(has.trigonometry){
specialFlag = true;
var trigSubgroupIndexes = [];
var trigTypes = [];
var trigsMultiplied = 1;
this.result[i][k] = this.result[i][k].replace(/(?:arc)?(sin|cos|tan|cot){_(\d+)}/g, function(match, type, index){
trigSubgroupIndexes.push(parseInt(index));
if(match.includes("arc")){
trigTypes.push([true, type]);
}else{
trigTypes.push([false, type]);
}
return " ";
});
for(var l = 0; l < trigTypes.length; l++){
var inverseness = trigTypes[l][0];
var type = trigTypes[l][1];
var parameter = (degreeOption) ? convertToRadian(parseFloat(this.result[trigSubgroupIndexes[l]])) : parseFloat(this.result[trigSubgroupIndexes[l]]);
var result;
if(inverseness){
switch(type){
case "sin":
result = Math.asin(parameter);
break;case "cos":
result = Math.acos(parameter);
break;case "tan":
result = Math.atan(parameter);
break;case "cot":
result = 1 / Math.atan(parameter);
break;
}
}else{
switch(type){
case "sin":
result = Math.sin(parameter);
break;case "cos":
result = Math.cos(parameter);
break;case "tan":
result = Math.tan(parameter);
break;case "cot":
result = 1 / Math.tan(parameter);
break;
}
}
trigsMultiplied *= result;
}
totalMultiplication *= trigsMultiplied;
}
if(has.logarithm){
specialFlag = true;
var logSubgroupIndexes = [];
var logsMultiplied = 1;
this.result[i][k] = this.result[i][k].replace(/log{_(\d+)}{_(\d+)}/g, function(match, firstIndex, secondIndex){
logSubgroupIndexes.push([parseInt(firstIndex), parseInt(secondIndex)]);
return " ";
});
for(var l = 0; l < logSubgroupIndexes.length; l++){
var base = this.result[logSubgroupIndexes[l][0]];
var power = this.result[logSubgroupIndexes[l][1]];
logsMultiplied *= (Math.log(power) / Math.log(base));
}
totalMultiplication *= logsMultiplied;
}
if(has.subgroup){
specialFlag = true;
var subgroupIndexes = [];
var groupsMultiplied = 1;
this.result[i][k] = this.result[i][k].replace(/{_(\d+)}/g, function(match, index){
subgroupIndexes.push(parseInt(index));
return " ";
});
for(var l = 0; l < subgroupIndexes.length; l++){
groupsMultiplied *= this.result[subgroupIndexes[l]];
}
totalMultiplication *= groupsMultiplied;
}
if(has.x){
specialFlag = true;
var powerX = countChar(this.result[i][k], "x");
this.result[i][k] = this.result[i][k].replace("x", " ");
totalMultiplication *= Math.pow(x, powerX);
}
if(specialFlag == true){
var factors = this.result[i][k].match(/\d+/g);
if(factors !== null){
for(var l = 0; l < factors.length; l++){
totalMultiplication *= parseFloat(factors[l]);
}
}
if(!isFinite(totalMultiplication) || checkNum(this.result[i][k]) || this.result[i][k].includes("(") || this.result[i][k].includes(")")){
this.result[i][k] = NaN;
}else{
this.result[i][k] = totalMultiplication;
}
}
}
var operators = ["^","*","/","+","-"];
for(var k = 0; k < operators.length; k++){
var search = this.result[i].indexOf(operators[k]);
while(search != -1){
switch(operators[k]){
case "+":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) + checkParse(this.result[i][search+1]));
break;case "-":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) - checkParse(this.result[i][search+1]));
break;case "*":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) * checkParse(this.result[i][search+1]));
break;case "/":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) / checkParse(this.result[i][search+1]));
break;case "^":
this.result[i].splice(search-1, 3, Math.pow(checkParse(this.result[i][search-1]) , checkParse(this.result[i][search+1])));
break;
}
if(this.result[i].indexOf(operators[k], search) == -1){
break;
}else{
search = this.result[i].indexOf(operators[k], search);
}
}
}
}
if(isNaN(this.result[0][0])){
this.result = "An error has occured, please make sure the parameters are correct.";
}else{
this.result = this.result[0][0];
}
}
functions.js
function countChar(str, character){
return str.toString().split(character).length-1;
}
function markChar(str, character){
var charCount = str.split(character).length;
var result = [];
for(var i = 0; i < charCount - 1; i++){
if(result.length == 0){
result.push(str.indexOf(character));
}else{
result.push(str.indexOf(character, result[i-1] + 1));
}
}
return result;
}
function changeAt(str, startingIndex, endingIndex, replacement){ // Returns the given string with the part between startingIndex and endingIndex replaced with replacement.
return str.substring(0, startingIndex) + replacement + str.substring(endingIndex, str.length);
}
function checkParse(str){
if(/[a-z]/.test(str) || countChar(str, ".") > 1){
return NaN;
}else{
return parseFloat(str);
}
}
function checkNum(str){
return (/[a-z]/.test(str) || countChar(str, ".") > 1);
}
function convertToRadian(degrees) {
return degrees * Math.PI / 180;
}
It works as intended when done like above. It puts values to x according to the range specified in the for loop in main.js and console.logs the results. But I don't want to create splittingOperators object everytime I recalculate with another x value. It's unnecessary since the actual formula stays the same.
var button1 = document.getElementById("button");
var text1 = document.getElementById("text");
var output = document.getElementById("result");
button1.addEventListener("click", function(){
var textInput = text1.value;
var cleared = new clearingUnwantedCharacters(textInput);
var marked = new subgroupMarking(cleared.output);
var prioritizedList = new subgroupPrioritization(marked.parenGroups);
var splittedPieces = new splittingOperators(prioritizedList.prioritizedGroups);
for(var i = 0; i <= 360; i++){
var calculatedPieces = new calculatePieces(splittedPieces.seperatedPieces, i, true);
console.log(calculatedPieces.result);
}
});
When I put the object creation outside of the for loop, it calculates and logs the first x value, but it gives
Uncaught TypeError: this.result[i][k].includes is not a function
as error after that. I suspect it's because it changes splittedPieces.seperatedPieces when it shouldn't. I couldn't find any reason for it to do that or maybe I am missing something.
I am trying to add values in a multidimensional array in JavaScript, but it doesn't seem to work. I get "variable not defined" error in snippet but can't see any variable which is not defined.
Does anyone have any idea what's going wrong here?
Many Thanks,
Hassam
var abc = "11:00, 11:10, 12:20,12:30";
var split = abc.split(",")
var limits = new Array();
var alltimes = [[],[]];
//var split = ["11:00", "11:10", "12:20","12:30"];
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
// alert(split.length );
if(i%2 === 1) // If odd value
{
alert(limits);
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
// alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
This is my JavaScript code
$(document).ready(function(){
$('.timepicker').click(function(){
var ajaxurl = 'Ajax.php',
data = {'action': 'Hassam'};
$.post(ajaxurl, data, function (response) {
// $('#timepicker').timepicker('option', 'disableTimeRanges', [abc]);
var split = response.split(",");
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
alert(split.length );
if(i%2 === 1) // If odd value
{
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
});
There is very simple solution to achieve what you want.
var split = ["11:00", "11:10", "12:20", "12:30"];
var alltimes = [];
while (split.length) {
alltimes.push(split.splice(0, 2));
}
console.log(alltimes);
When a button is clicked i want the results in the array to be listed for example: John Smith 16, Jack Snow 10 etc..
I want to use a loop however the code in my loop is incorrect at the moment as when i click the button all i get is: [object Object].
Can someone provide a possible fix?
function begin() {
listresults();
();
}
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
function listresults() {
var text = "";
var total = 0;
var i;
for (i in results) {
text += results[i] + "<br>";
}
document.getElementById('message').innerHTML = text;
}
I would first check that the lengths of the 2 arrays are the same. Then iterate using a for loop:
final int timeLength = TIME.length;
if (timeLength != stat.size()) {
//something may not be right
}
for (int i = 0; i < timeLength; i++) {
System.out.println(time[i]+" "+stat.get(i));
}
You are pushing objects results1, results2, etc in the array 'results'.
So while iterating the array you should access the object properties as shown below:
function listresults() {
var text = "";
var total = 0;
var i;
for (i in results) {
text += results[i]['name'] + ' ' + results[i]['score'] + "<br>";
}
As you are appending objects instead of object values in the filed.
This is the proper way of accessing name and score from object which is returned when you are looping through your array of objects :
function begin() {
listresults();
();
}
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
function listresults() {
var text = "";
var total = 0;
for (var i=0; i < results.length; i++) {
text += results[i].name + " " + results[i].score + "<br>";
}
document.getElementById('message').innerHTML = text;
}
Here is an Jsfiddle example
Recommend you to use Array methods(map, join) instead of pure loops
function begin() {
listresults();
}
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
function listresults() {
document.getElementById('message').innerHTML =
results.map(function(item) {
return item.name + ' ' + item.score;
}).join('<br>');
document.getElementById('total').innerHTML =
results.map(function(item) {
return item.score;
}).reduce(function(sum, score) {
return sum + score;
}, 0);
}
<button onclick="begin()">begin</button>
<br />
<div id="message"></div>
<div>total: <span id="total">0</span></div>
Use Array.map() and Array.join()
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
var res = results.map(item => { return item.name+ " " +item.score });
console.log(res.join(", "));
I have the below JavaScript running on one of my forms OnLoad event :-
function calcServicePriceTotal() {
var grid = document.getElementById('ProjectServicesGrid');
var ids = grid.control.get_allRecordIds();
var sum = 0.00;
var cellValue;
for (i = 0; i < ids.length; i++) {
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);
}
Unfortunately I get the following error :-
"Error:'subGridOnload' is undefined"
I believe that the script is firing before the object has had the time it needs to load so what can I do to slow down the function? There must be some way to overcome this but I am far from a JavaScript expert so I could use some help.
Thanks in advance
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();", 500);
}
}
var select = [];
for (var i = 0; i < nameslots; i += 1) {
select[i] = this.value;
}
This is an extract of my code. I want to generate a list of variables (select1, select2, etc. depending on the length of nameslots in the for.
This doesn't seem to be working. How can I achieve this? If you require the full code I can post it.
EDIT: full code for this specific function.
//name and time slots
function gennametime() {
document.getElementById('slots').innerHTML = '';
var namelist = editnamebox.children, slotnameHtml = '', optionlist;
nameslots = document.getElementById('setpresentslots').value;
for (var f = 0; f < namelist.length; f += 1) {
slotnameHtml += '<option>'
+ namelist[f].children[0].value
+ '</option>';
};
var select = [];
for (var i = 0; i < nameslots; i += 1) {
var slotname = document.createElement('select'),
slottime = document.createElement('select'),
slotlist = document.createElement('li');
slotname.id = 'personname' + i;
slottime.id = 'persontime' + i;
slottime.className = 'persontime';
slotname.innerHTML = slotnameHtml;
slottime.innerHTML = '<optgroup><option value="1">00:01</option><option value="2">00:02</option><option value="3">00:03</option><option value="4">00:04</option><option value="5">00:05</option><option value="6">00:06</option><option value="7">00:07</option><option value="8">00:08</option><option value="9">00:09</option><option value="10">00:10</option><option value="15">00:15</option><option value="20">00:20</option><option value="25">00:25</option><option value="30">00:30</option><option value="35">00:35</option><option value="40">00:40</option><option value="45">00:45</option><option value="50">00:50</option><option value="55">00:55</option><option value="60">1:00</option><option value="75">1:15</option><option value="90">1:30</option><option value="105">1:45</option><option value="120">2:00</option></optgroup>';
slotlist.appendChild(slotname);
slotlist.appendChild(slottime);
document.getElementById('slots').appendChild(slotlist);
(function (slottime) {
slottime.addEventListener("change", function () {
select[i] = this.value;
});
})(slottime);
}
}
You'll have to close in the iterator as well in that IIFE
(function (slottime, j) {
slottime.addEventListener("change", function () {
select[j] = this.value;
});
})(slottime, i);
and it's only updated when the element actually change
The cool thing about JavaScript arrays is that you can add things to them after the fact.
var select = [];
for(var i = 0; i < nameSlots; i++) {
var newValue = this.value;
// Push appends the new value to the end of the array.
select.push(newValue);
}