Summary:
I have a code that takes words from a database, it puts it all in a box which has 3 by 3 text boxes (you can also expand instead of using 3 boxes, which I confirmed worked).
Inside the boxes, it takes the height of the words and sets that height to the height of the div holding the words, then places that height inside of a array. If a div is not there (no text), it places a 0.
Every 3rd time it does this, which is 1 row, it will check the height of the three in the row, and set the div above them as the biggest height, like so:
var tempN = 0; //Holds each number temporarily
var temp = []; //Holds all 9 box heights
for (var i = 0; i < Panels.length; i++) { //There are 9 panels
temp[i] = new Array(); //adding to array
if (document.getElementById('Column'+i+Id[Ten])!=null) {//Id[Ten] will be 3, 2, and 1, in a for loop
document.getElementById('Column'+i+Id[Ten]).style.height = document.getElementById('Text'+i+Id[Ten]).clientHeight+"px";
temp[i].push(document.getElementById('Column'+i+Id[Ten]).clientHeight); //puts number on table
} else {
temp[i].push(0); //since there is no panel, the height would be 0
}
if (i%3 == 2) { //every 3rd time
for (var x=2;x >= 0;x--) { //also could do (var x=0;x<3;x++)
alert(temp[i-x]+" is greater than "+tempN); //tells me what should work
if (tempN < temp[i-x]) { //also could do the other way around
tempN = temp[i-x]; //tempN will be the current biggest height
alert(tempN+' '+temp[i-x]); //just a show it went through if
document.getElementById('Row'+BoxRow+Id[Ten]).style.height = tempN + "px";
}
}
tempN = 0; //reset tempN for next 3 boxes
}
}
temp = []; //reset temp for next box
Now, the way my page is, temp will be:
temp = [0,158,0,0,158,0,0,50,0] when Id[Ten] is 3
temp = [0,50,0,0,0,0,0,0,0] when Id[Ten] is 2
temp = [284,50,50,50,50,50] when Id[Ten] is 1
The Problem:
when my code gets to Id[Ten] is 1, It will start by saying:
"284 is greater than 0"
which is planned, then I get:
"284 284"
which is also planned, then:
"50 is greater than 284"
Here is the problem: what came after that is what should have been skipped:
"50 50"
This tells me that the if statement I have passed True once it saw 284 < 50. I have done math at least more than once in my life, and I know 284 is a bigger number than 50. Due to this, my box has a smaller height than the text in it, and they overlap in an way uglier than me. I'm sure my code and I are having some kind of mid-life crisis, and would be great if someone can explain to me why my code is going through this rebellious stage.
This is caused because you are comparing string to string, when comparing string js verify only your alphabetical order.
You have to use parseInt in your variables.
This is the test I did in the chrome console.
var test1 = 50
var test2 = 200;
test1 > test2
false
--------
var test1 = "50"
var test2 = "200";
test1 > test2
true
parseInt(test1) > parseInt(test2)
false
Your code is comparing strings (alphabetical order):
"Zoo" > "Apple" // true
"50" > "284" // true
You need to compare numbers by using something like parseInt:
parseInt("50") > parseInt("284"); // false
var stringResult = "50" > "284"; // true
var intResult = parseInt("50") > parseInt("284"); // false
document.getElementById('strings').textContent = stringResult;
document.getElementById('ints').textContent = intResult;
<h3>Result of "50" > "284" =
<span id="strings"></span>
</h3>
<h3>
Result of parseInt("50") > parseInt("284") =
<span id="ints"></span>
</h3>
In javascript everything is an object.It does not has any type
It determines type by the way we declare it
Here you are comparing (tempN < temp[i-x])
tempN and temp[i-x] both are strings
you have to convert them to numbers and then compare
var number1=parseInt(tempN,10);
var number2=parseInt(temp[i-x],10);
console.log(number1<number2);
If you want to convert array of numbers to get sorted but not alphabetically you can do something like this
var numbers=[1,90,5,8];
numbers.sort(SortCompare);
function SortCompare(a,b){
return a-b;
}
Hope this helps
Related
I've written some code which is a basic up/down voting list.
https://alasdairjames.github.io/up-down-counter1/
This works absolutely fine, apart from with the last list item. All the other list items up and down vote as they should.
With the last list item, if I 'down' vote it a few times, and then 'up' vote it, even if its counter is lower than its parent prev sibling counter, the if statement somehow still runs.
I've checked through all the code and I can't see where the problem is.
//Move it up
$(".testMoveUp").on("click", function(event){
// select the counter, increase it
const counter = $(event.target).siblings(".datasetCounter");
let counterNew = +$(counter).text()+1;
$(counter).text(counterNew);
//select this and previous counters
var thisCounter = $(event.target).siblings(".datasetCounter").text();
var prevCounter = $(event.target).parent().prev().children(".datasetCounter").text();
console.log(thisCounter);
console.log(prevCounter);
//move if appropriate
if ( thisCounter > prevCounter) {
var parent = $(event.target).parent();
var prevParent = $(event.target).parent().prev();
$(parent).insertBefore(prevParent);
}
});
//Move it down
$(".testMoveDown").on("click", function(event){
// select the counter, increase it
const counter = $(event.target).siblings(".datasetCounter");
let counterNew = $(counter).text()-1;
$(counter).text(counterNew);
//select this and previous counters
var thisCounter = $(event.target).siblings(".datasetCounter").text();
var nextCounter = $(event.target).parent().next().children(".datasetCounter").text();
console.log(thisCounter);
console.log(nextCounter);
//move if appropriate
if ( thisCounter < nextCounter) {
var parent = $(event.target).parent();
var nextParent = $(event.target).parent().next();
$(parent).insertAfter(nextParent);
}
});
if (thisCounter < nextCounter) -- you compare strings here, not numbers.
Use parseInt() to store numeric values in thisCounter and nextCounter:
var thisCounter = parseInt($(event.target).siblings(".datasetCounter").text(), 10);
The problem is on this two lines:
var thisCounter = $(event.target).siblings(".datasetCounter").text();
var nextCounter = $(event.target).parent().next().children(".datasetCounter").text();
You are getting the text value and comparing it.
The easier way to fix it is just to parse the texts to numbers. Since you are sure they will always be numbers, you can simply add '+' on your comparisons:
if (+thisCounter < +nextCounter) {
...
}
Note: remember to add it to both comparisons, not only one
String "9" is greater than string "10". Make sure to convert your values to numbers before comparing them.
first sorry my english.
Im making a little program to sort football players into two teams, A and B.
6 players, 3 for A and 3 for B. With a random number generator of course.
In Java i have no problem, i made this program and runs perfect, but i dont know much about JS and array item removings seems a little diferent here.
My code:
function hola(){
var primero = document.getElementById("1").value;
var segundo = document.getElementById("2").value;
var tercero = document.getElementById("3").value;
var cuarto = document.getElementById("4").value;
var quinto = document.getElementById("5").value;
var sexto = document.getElementById("6").value;
var jugadores = [primero,segundo,tercero,cuarto,quinto,sexto];
var eq1=[];
var eq2=[];
while (jugadores.length > 0){
var largoArray = jugadores.length;
var rand = Math.round(Math.random()* largoArray);
console.log("before the if, array jugadores haves ",jugadores.toString() ," and his size is ",jugadores.length);
if (eq1.length < 3){
eq1.push(jugadores[rand]);
remove(jugadores,jugadores[rand]);
}else {
eq2.push(jugadores[rand]);
remove(jugadores,jugadores[rand]);
}
}
document.getElementById("resultado").innerHTML= eq1 + " y el equipo B: " + eq2;
console.log("equipo 1 ", eq1);
console.log("equipo 2", eq2);
}
function remove(array, element) {
const index = array.indexOf(element);
if (index !== -1) {
array.splice(index, 1);
}
}
and it return to me:
"equipo 1 (3) [undefined, "iniesta", "ronaldo"]
script2.js:35 equipo 2 (4) ["messi", "ronaldinho", "maradona", "pele"]"
also the console logs i made to depurate seems to work fine...
The array is 1 element shorter each cicle, and array.lenght match the desired sizes.
What am doing wrong?
The problem is on the line:
Math.round(Math.random() * largoArray)
Since that will sometimes return an index that is beyond the bounds of the array. When that happens, this code:
eq1.push(jugadores[rand]);
remove(jugadores,jugadores[rand]);
Won't work, since jugadores[rand] is undefined, so you end up pushing undefined into one of your arrays, without removing anything from the original jugadores array.
To fix this, use the Math.floor function instead, changing the line to:
Math.floor(Math.random() * largoArray)
Arrays (like Java) start with the index 0.
The range of random numbers you are generating varies from 0 to 6 (array has only 6 elements).
var rand = Math.round(Math.random()* largoArray);
Instead use,
var rand = Math.round((Math.random()* largoArray)-1);
in a Podio calculation_field A I sum up the numbers of each related item (from another app) which contain "searchstring_1" in a text_field, in calculation_field B all related items which contain "searchstring_2"
No problem with the following code - IF there exists a related item. But if there exists no related item the "1" (= "nothing found"?) is displayed as "result". I tried several things, but can't find a solution for a calculation like: IF there is no related item then result = 0 (or "" or null), else let run the for-loop. Has anybody a tip what I can do?
Thanks,
Rainer
var str = all of text_field;
var num = all of number_fields;
var total = 0;
for(var i = 0; i < num.length ; i++) {
if (str[i].indexOf("searchstring_1") === 0) {
total += num[i];
}
}
The calculation field always returns the last used value if you don't explicitly specify the return value. Maybe in your case the last value of i, str[i].indexOf("searchstring_1") would return -1, I think...
To make sure that the value of totalis returned, simply add
total;
at the end of your calculation field value.
Enjoy,
Michael / Hamburg
So I have 11 checkboxes that are split up into 4 different categories. Each category has 3 check-boxes to choose from except for the last, which has 2. I want to check if a check-box within each category is checked and find out how many of them are checked within that category. I might be over thinking this one but so far I have this as my JS:
//I initially receive the checkbox values as a string that has 1 for checked and 0 for not checked.
var split_string = checkbox_string.split(",").map(Number);
console.log(split_string);
var sec = [];
var total = 0;
var split_int=[];
var sliced = 0;
for (var i = 0; i <= 3 ; ++i) {
sec[i] = split_string.splice(0,3);
console.log(sec[i]);
for(var j = 0; j < sec[i].length; ++j){
sliced = sec[i][j];
total += sliced;
}
console.log("total= "+ total);
window['section' + i] = total;
}
So as of right now I'm pretty close, although I'm sure there is a simpler way of doing this. I split the string into 4 arrays (ex.[1,0,1] [0,0,1] [1,1,1] [1,0]). Then I take each individual number from each array and add it to the total.
As of right now it will return the 1st three added, then it returns the 2nd three added to the first three on its 2nd loop. So for example total=2 the first time around then total=3 the 2nd time around, but I want total the 2nd time around to be only based on the 2nd array (so it would be 1 if following the ex. above).
function summer(p,c,i) {
if( i%3==0 ) p.push(0);
p[p.length-1] += c;
return p;
}
var split_string = [1,0,1,0,0,1,1,1,1,1,0];
split_string.reduce(summer,[]); // [2, 1, 3, 1]
Well I'm dumb, all I needed to add was total = 0 at the bottom of the array. But I'd still be interested if there is better/more simple ways of doing this.
Hi I have code like this:
$('#Generator_Rzutow').click (function(){
var val1 = $('#rzucane').val();
var val2 = $('#zachowywane').val();
var zbior = [];
var limit = 10;
alert (val1);
alert (val2);
for (var i=0; i<val1;i++){
var wynik_rzutu = 1+Math.floor(Math.random()*10);
if (wynik_rzutu<limit){
zbior.push(wynik_rzutu);
} else {
limit = limit+10;
wynik_rzutu = wynik_rzutu+1+Math.floor(Math.random()*10);
if (wynik_rzutu<limit){
zbior.push(wynik_rzutu);
} else {
limit = limit+10;
wynik_rzutu = wynik_rzutu+1+Math.floor(Math.random()*10);
zbior.push(wynik_rzutu);
}
}
}
$('#wypisz').text (zbior);
});
My problem is that when it randoms '10' it sometimes add 10 to array, when it should randomize another time and ad it to prev value.
My second question is. How to get it to randomize another value and ad it to prev as long as it randomize 10. For ex: so it could get numer 74, when it randomize 7x10 and 4, and then it past it to array.
I know I should do it by while lop but I couldn`t get working solition, so instead I put 'if'
The first problem is that you don't reset your limit at each iteration. You start with limit 10, then when the first number larger than 10 is generated, the limit is increased to 20 and all subsequent numbers will be compared to 20 to see if they are added to the array or re-generated (and they will all be added to the array, since they are all smaller than 20).
As for your second problem, i think this piece of code behaves accordingly:
for (var i=0; i<val1;i++){
var wynik_rzutu = 0, limit = 0;
while (wynik_rzutu >= limit) {
wynik_rzutu += 1+Math.floor(Math.random()*10);
limit += 10;
}
zbior.push(wynik_rzutu);
}
You can also add a counter to prevent it from an infinite cycle (if Math.random() always returns 0.9 for example), but i doubt it is something you really require.