Basically what I want to do is create list of characters with format like excel column name.
for example :
a,b,c,d,.....,z,aa,ab,ac,....,yz
in php you can just looping it with this code:
for($char = "A"; $char <= "Z"; $char++)
{
echo $char . "\n";
}
but when I try it in javascript :
var i3;
var text3 = "";
for(i3 = "A"; i3 <= "Z"; i3++)
{
text3 += i3 + ", ";
}
document.getElementById("pId").innerHTML = text3;
It doesn't work for me. Are there some errors in my code? Or that PHP logic doesn't work in JS? If you know how to make one please tell me, thanks.
In javacript the incrementor operator will return NaN when called on a string value.
You can use ascii code based implementation like
var i3, i4;
var text3 = "";
for (i3 = 0; i3 < 26; i3++) {
text3 += String.fromCharCode(97 + i3) + ", ";
}
for (i3 = 0; i3 < 26; i3++) {
for (i4 = 0; i4 < 26; i4++) {
text3 += String.fromCharCode(97 + i3) + String.fromCharCode(97 + i4) + ", ";
}
}
document.getElementById("pId").innerHTML = text3;
<span id="pId"></span>
Short is beautiful!
var nextChar = c=>c?String.fromCharCode(c.charCodeAt(0)+1):'A';
var nextCol = s=>s.replace(/([^Z]?)(Z*)$/, (_,a,z)=>nextChar(a) + z.replace(/Z/g,'A'));
//test:
nextCol(''); //A
nextCol('A'); //B
nextCol('Z'); //AA
nextCol('AA'); //AB
nextCol('XYZ'); //XZA
nextCol('ZZZZ'); //AAAAA
//output: A,B,C,...,ZZ
for(var i=0, s=''; i<702; i++){
s = nextCol(s);
console.log(s);
}
//output: A,B,C,...,ZZZZ
for(var i=0, s=''; i<475254; i++){
s = nextCol(s);
console.log(s);
}
I worked on a function called next, which provides the adjacent right cell.
function next(currentCell) {
let regex = /[A-Z]/g;
let numberRegex = /[0-9]/g;
let chars = currentCell.match(regex);
let nums = currentCell.match(numberRegex);
let flag = true;
let x = 1;
while (flag) {
if (chars[chars.length - x] === 'Z') {
if ((chars.length - x) === 0) {
chars[chars.length - x] = 'A';
chars.unshift('A');
flag = false;
} else {
chars[chars.length - x] = 'A';
x++;
}
} else {
chars[chars.length - x] = String.fromCharCode(chars[chars.length - x].charCodeAt(0) + 1);
flag = false;
}
}
return chars.join("") + nums.join("");
}
next('A1') // returns 'B1'
next('ZZ90') // returns 'AAA90'
Please try the below code to get done with javascript
var i3;
var text3 = "";
var c;
for(i3 = 65; 90 >= i3; i3++)
{
c = String.fromCharCode(i3);
text3 += c + ", ";
}
document.getElementById("pId").innerHTML = text3;
Related
I'm trying to create a program where if the user enters a X-number between 1-9, and it takes that X-number and creates X-number of rows and columns. For example, if the user enters "5", the output should be something like this:
....1
...2.
..3..
.4...
5....
I cannot get it to show the output right now with the code I have. I am still new to JavaScript so any help is appreciated.
function drawSquare() {
let myArray1 = ["1"];
let myArray2 = [".1", "2."];
let myArray3 = ["..1", ".2.", "3.."];
let myArray4 = ["...1", "..2.", ".3..", "4..."];
let myArray5 = ["....1", "...2.", "..3..", ".4...", "5...."];
let myArray6 = [".....1", "....2.", "...3..", "..4...", ".5....", "6....."];
let myArray7 = ["......1", ".....2.", "....3..", "...4...", "..5....", ".6.....", "7......"];
let myArray8 = [".......1", "......2.", ".....3..", "....4...", "...5....", "..6.....", ".7......", "8......."];
let myArray9 = ["........1", ".......2.", "......3..", ".....4...", "....5....", "...6.....", "..7......", ".8.......", "9........"];
let l1 = myArray1.length;
let l2 = myArray2.lenght;
let l3 = myArray3.length;
let l4 = myArray4.length;
let l5 = myArray5.length;
let l6 = myArray6.length;
let l7 = myArray7.length;
let l8 = myArray8.length;
let l9 = myArray9.length;
let number = document.getElementById("textbox3")
let getNumber = number.value
if (getNumber != 1 || getNumber > 9) {
alert("You have entered an incorrect number");
} else if (getNumber = 1){
text = "<br>";
for (i = 0; i < l1; i++) {
text += "<br>" + myArray1[i] + "<br>";
}
}
}
<p>Enter a height for our square<input type="text" id="textbox3"><button id="drawSqaure" onclick="drawSquare()">Draw Square</button></p>
<p id="output2">Output goes here</p>
Little implementation using a textarea. It uses the number of rows to draw to know how many dots to draw, depending upon which row you are drawing.
document.getElementById('rowCount').addEventListener('input', function(e){
var rowCount = parseInt(e.target.value.trim() || '0', 10);
var textarea = document.getElementsByTagName('textarea')[0];
textarea.innerHTML = '';
for (var i = 1; i <= rowCount; i++) {
if (i > 1) textarea.innerHTML += "\n";
textarea.innerHTML += '.'.repeat(rowCount - i);
textarea.innerHTML += i;
textarea.innerHTML += '.'.repeat(i - 1);
}
});
<input type="number" id="rowCount" value="0" min="0">
<textarea></textarea>
To make it the way you clearly said on your question:
. . . . 1
. . . 2 .
. . 3 . .
. 4 . . .
5 . . . .
The solution is this:
$("#generate_square").click(function(){
let number = $("#number").val();
let square = $("#square_gen");
let str = "";
let number_shown = 1;
for(var dcolumns = 1; dcolumns<=number; dcolumns++){
for(var drows = 1; drows<=number; drows++){
if( drows === number_shown ){
str += number_shown+" ";
}else{
str +="0 ";
}
}
str += "<br>";
number_shown++;
}
square.append(str);
});
Here is a fiddle of it working:
https://jsfiddle.net/ndpe671c/1/
function drawSquare() {
var n = document.getElementById("textbox3").value;
n = parseInt(n);
var str = '<br/>';
for (var i = 0; i < n; i++ ) {
var x = n - 1;
for (var j = x; j >= 0; j--) {
if (j === i) {
str += i;
} else {
str += '.';
}
}
str += '<br/>';
}
// console.log(str);
$('#output2').html(str);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Enter a height for our square<input type="text" id="textbox3"><button id="drawSqaure" onclick="drawSquare()">Draw Square</button></p>
<p id="output2">Output goes here</p>
I make it simpler with jquery. Check it and tell me, if it's what you want.
function goOneYear() {
//changing the value of the no rabbits entree
var x = parseInt(document.getElementById("numRabbits").value) + parseInt(document.getElementById("rateBirth").value) * birthRate - parseInt(document.getElementById("rateDeath").value) * deathRate;
if (x < 2000) {
alert("FOX HUNT");
}
document.getElementById("numRabbits").value = x;
//incementing year by 1
document.getElementById("numYears").value++;
//adding this year to the list
var temp = "";
for (int i = 0; i < parseInt(document.getElementById("numRabbits").value); i++) {
temp += "*";
}
printTable.push(document.getElemernyById("numYears").value + " " + temp);
//making the text area the new set
if (document.getElementById("drawGraph").checked == true) {
if (temp.length > document.getElementById("rabbitTable").cols) {
document.getElementById("rabbitTable").cols = temp.length;
}
document.getElementById("rabbitTable").rows = printTable.length;
changeTextArea();
}
//setting conditions back to normal
setRabbitConditions(document.getElementById("normal"));
setRates("normal");
}
use var i = 0 instead of int i = 0
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
}
I wrote this code in my html site, in Javascript, but is not working right. Most times it seems to ignore some entries and just randomly selects which is the min/max value. Also, when I tried to calculate average values, I got a string instead of a number, even though the variable is declared as 0 in the beginning. e.g performing 0+1+1+2+3+5 = 011235 instead of 12.
Here is the code, thanks in advance.
**EDIT: I added the student average code in the end, but it doesn't work, it doesn't show any results on the page, not even the "student" + [i] part. On the other hand, the parseInt() command worked, and made everything work as it should, thank you :)
<script language = "javascript">
function myFunction() {
var course0 = [];
var course1 = [];
var course2 = [];
var minstugrade = 100;
var maxstugrade = 0;
var minstugradetext = "";
var maxstugradetext = "";
var stuavgarr = [];
var minstuavg = 100;
var maxstuavg = 0;
var minstuavgtext = "";
var maxstuavgtext = "";
var mincougrade = 100;
var maxcougrade = 0;
var mincougradetext = "";
var maxcougradetext = "";
var mincouavg = 100;
var maxcouavg = 0;
var mincouavgtext = "";
var maxcouavgtext = "";
var couavg = 0;
//add form items to array
var x = document.getElementById("course0");
var i;
for (i = 0; i < x.length ;i++) {
course0.push(parseInt(x.elements[i].value));
}
var x = document.getElementById("course1");
var i;
for (i = 0; i < x.length ;i++) {
course1.push(parseInt(x.elements[i].value));
}
var x = document.getElementById("course2");
var i;
for (i = 0; i < x.length ;i++) {
course2.push(parseInt(x.elements[i].value));
}
//calculate course & student min/max
for (i = 0; i < course0.length; i++) {
if (course0[i] < mincougrade) {
mincougrade = course0[i];
mincougradetext = "course0";
}
if (course0[i] > maxcougrade) {
maxcougrade = course0[i];
maxcougradetext = "course0";
}
if (course0[i] < minstugrade) {
minstugrade = course0[i];
minstugradetext = "student" + [i];
}
if (course0[i] > maxstugrade) {
maxstugrade = course0[i];
maxstugradetext = "student" + [i];
}
}
for (i = 0; i < course1.length; i++) {
if (course1[i] < mincougrade) {
mincougrade = course1[i];
mincougradetext = "course1";
}
if (course1[i] > maxcougrade) {
maxcougrade = course1[i];
maxcougradetext = "course1";
}
if (course1[i] < minstugrade) {
minstugrade = course1[i];
minstugradetext = "student" + [i];
}
if (course1[i] > maxstugrade) {
maxstugrade = course1[i];
maxstugradetext = "student" + [i];
}
}
for (i = 0; i < course2.length; i++) {
if (course2[i] < mincougrade) {
mincougrade = course2[i];
mincougradetext = "course2";
}
if (course2[i] > maxcougrade) {
maxcougrade = course2[i];
maxcougradetext = "course2";
}
if (course2[i] < minstugrade) {
minstugrade = course2[i];
minstugradetext = "student" + [i];
}
if (course2[i] > maxstugrade) {
maxstugrade = course2[i];
maxstugradetext = "student" + [i];
}
}
//calculate course average
for (i = 0; i < course0.length; i++) {
couavg += course0[i];
}
couavg = couavg / course0.length
if (couavg < mincouavg) {
mincouavg = couavg;
mincouavgtext = "course0";
}
if (couavg > maxcouavg) {
maxcouavg = couavg;
maxcouavgtext = "course0";
}
couavg = 0;
for (i = 0; i < course1.length; i++) {
couavg += course1[i];
}
couavg = couavg / course1.length
if (couavg < mincouavg) {
mincouavg = couavg;
mincouavgtext = "course1";
}
if (couavg > maxcouavg) {
maxcouavg = couavg;
maxcouavgtext = "course1";
}
couavg = 0;
for (i = 0; i < course2.length; i++) {
couavg += course2[i];
}
couavg = couavg / course2.length
if (couavg < mincouavg) {
mincouavg = couavg;
mincouavgtext = "course2";
}
if (couavg > maxcouavg) {
maxcouavg = couavg;
maxcouavgtext = "course2";
}
//calculate student average
for (i = 0; i < course0.length; i++) {
stuavgarr[i] += course0[i];
stuavgarr[i] += course1[i];
stuavgarr[i] += course2[i];
}
for (i=0; i < stuavgarr.length; i++) {
stuavgarr[i] = stuavgarr[i] / course0.length;
if (stuavgarr[i] < minstuavg) {
minstuavg = stuavgarr[i];
minstuavgtext = "student" + [i];
}
if (stuavgarr[i] > maxstuavg) {
maxstuavg = stuavgarr[i];
maxstuavgtext = "student" + [i];
}
}
document.getElementById("studmaxgrade").innerHTML = "Student that achieved the max grade is " + maxstugradetext
document.getElementById("studmingrade").innerHTML = "Student that achieved the min grade is " + minstugradetext
document.getElementById("studmaxavg").innerHTML = "Student that achieved the max average is " + maxstuavgtext
document.getElementById("studminavg").innerHTML = "Student that achieved the min average is " + minstuavgtext
document.getElementById("courmaxgrade").innerHTML = "The course in which the max grade is scored is " + maxcougradetext
document.getElementById("courmingrade").innerHTML = "The course in which the min grade is scored is " + mincougradetext
document.getElementById("courmaxavg").innerHTML = "The course in which the max average grade is scored is " + maxcouavgtext
document.getElementById("courminavg").innerHTML = "The course in which the min average grade is scored is " + mincouavgtext
}
</script>
The value of an input is a string, thus a + b will be interpreted as appending one string to another.
If you make sure the first parameter (a in this case) is an integer a + b will result in the two being mathematically adding the two
console.log( '0' + 1 + 2 + 3 + 4 ); //* outputs 01234
console.log( parseInt( 0 ) + 1 + 2 + 3 + 4 ); //* outputs 10
JSFiddle
Ok for a start you seem very confused about
document.getElementById
This does not address a javascript variable at all......
This literally "gets the document element by its id".
Here is an example of how to use it...
<html>
<img id='my_new_selfie' src='me.jpg'>
....
....
<script>
alert (document.getElementById('my_new_selfie').src)
</script>
This would simply pop up an alert with the text that describes the src of the
document object who's id is 'my_new_selfie'
that is....
[me.txt]
The reason that document.getElementById was introduced to javascript was to save developers learning the DOM (document object model) in order to access objects.
It allows you to simply give you object an id and change things about it using the id
In the above example I could use a script or button to change the image source
an example of this might be using the onclick event of another object on the page like a button...
onclick='document.getElementById('my_new_selfie').src='new_pic_of_me.JPG'
It is not used to identify variables in a javascript
I followed a tutorial/modified the code to get a javascript tag cloud working in IBM Cognos (BI software). The tag cloud works fine in FireFox but in Internet Explorer I get the error:
"Message: '1' is null or not an object"
The line of code where this is present is 225 which is:
var B = b[1].toLowerCase();
I have tried many different solutions that I have seen but have been unable to get this working correctly, the rest of the code is as follows:
<script>
// JavaScript Document
// ====================================
// params that might need changin.
// DON'T forget to include a drill url in the href section below (see ###) if you want this report to be drillable
var delimit = "|";
var subdelimit = "[]"; // change this as needed (ex: Smith, Michael[]$500,000.00|)
var labelColumnNumber = 0; // first column is 0
var valueColumnNumber = 1;
var columnCount = 2; // how many columns are there in the list?
// ====================================
/*
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
*/
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return ( num );
}
function filterNum(str) {
re = /\$|,|#|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|/g;
// remove special characters like "$" and "," etc...
return str.replace(re, "");
}
table = document.getElementById("dg");
if ( table.style.visibility != 'hidden'){ //only for visible
/*alert('Visible');*/
tags = document.getElementById("dg").getElementsByTagName("SPAN");
txt = "";
var newText = "a";
for (var i=columnCount; i<tags.length; i++) {
/*
valu = filterNum(tags[i+valueColumnNumber].innerHTML);
txt += valu;
txt += subdelimit+tags[i+labelColumnNumber].innerHTML+delimit;
i = i+columnCount;
*/
if(i%2!=0){
var newValue = filterNum(tags[i].innerHTML);
}else var newName =tags[i].innerHTML;
if((i>2) & (i%2!=0)){
newText = newText+newValue+subdelimit+newName+delimit;
if(typeof newText != 'undefined'){
txt = newText;
txt = txt.substr(9);
/* alert(txt);*/
}
}
}
}/*else alert ('Hidden');*/
function getFontSize(min,max,val) {
return Math.round((150.0*(1.0+(1.5*val-max/2)/max)));
}
function generateCloud(txt) {
//var txt = "48.1[]Google|28.1[]Yahoo!|10.5[]Live/MSN|4.9[]Ask|5[]AOL";
var logarithmic = false;
var lines = txt.split(delimit);
var min = 10000000000;
var max = 0;
for(var i=0;i<lines.length;i++) {
var line = lines[i];
var data = line.split(subdelimit);
if(data.length != 2) {
lines.splice(i,1);
continue;
}
data[0] = parseFloat(data[0]);
lines[i] = data;
if(data[0] > max)
max = data[0];
if(data[0] < min)
min = data[0];
}lines.sort(function (a,b) {
var A = a[1].toLowerCase();
var B = b[1].toLowerCase();
return A>B ? 1 : (A<B ? -1 : 0);
});
var html = "<style type='text/css'>#jscloud a:hover { text-decoration: underline; }</style> <div id='jscloud'>";
if(logarithmic) {
max = Math.log(max);
min = Math.log(min);
}
for(var i=0;i<lines.length;i++) {
var val = lines[i][0];
if(logarithmic) val = Math.log(val);
var fsize = getFontSize(min,max,val);
dollar = formatCurrency(lines[i][0]);
html += " <a href='###Some drillthrough url which includes the param "+lines[i][1]+"' style='font-size:"+fsize+"%;' title='"+dollar+"'>"+lines[i][1]+"</a> ";
}
html += "</div>";
var cloud = document.getElementById("cloud");
cloud.innerHTML = html;
var cloudhtml = document.getElementById("cloudhtml");
cloudhtml.value = html;
}
function setClass(layer,cls) {
layer.setAttribute("class",cls);
layer.setAttribute("className",cls);
}
function show(display) {
var cloud = document.getElementById("cloud");
var cloudhtml = document.getElementById("cloudhtml");if(display == "cloud") {
setClass(cloud,"visible");
setClass(cloudhtml,"hidden");
}
else if(display == "html") {
setClass(cloud,"hidden");
setClass(cloudhtml,"visible");
}
}
generateCloud(txt);
</script>
Any help or explanations is much appreciated
Sorry, I'm not seeing where a[] and b[] are defined, is this done elsewhere? Firefox and IE may be responding differently to the problem of an undefined array.