I'm playing around with some HTML and Javascript. I'm trying to print out 100 numbers on a screen after I press a button on a webpage. I can get the numbers to print on the screen but when I want to replace a number with a string like "Apple" if the number is divisible by 5. The code is below:
function testFunction() {
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = -1; i < 20; i++) {
if (i % 5 == 0 && i % 3 == 0) {
myHTML += '<span class="test">Pineapple</span><br/>';
} else if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br/>';
} else if (i % 3 == 0) {
myHTML += '<span class="test">Pine</span><br/>';
} else {
myHTML += '<span class="test">' + (i + 1) + '</span><br/>';
}
}
wrapper.innerHTML = myHTML
}
The output is always off by one element so it would print "5" and then the next line would be "Apple" instead of replacing "5" with "Apple" and then printing "6"
Here is the output:
0
Pineapple
2
3
Pine
5
Apple
Pine
8
9
Pine
Apple
12
Pine
14
15
Pineapple
17
18
Pine
20
You are printing i+1, instead of i.
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = -1; i < 20; i++) {
if (i % 5 == 0 && i % 3 == 0) {
myHTML += '<span class="test">Pineapple</span><br/>';
} else if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br/>';
} else if (i % 3 == 0) {
myHTML += '<span class="test">Pine</span><br/>';
} else {
myHTML += '<span class="test">' + (i ) + '</span><br/>';
}
}
wrapper.innerHTML = myHTML
}
The trouble is in the starting point of your for loop, where you initialize with -1 instead of 0. While you use (i + 1) at the end when you print a number, which is why it causes your results to be one number off.
Use for(var i = 0; i <= 20; i++) instead of for (var i = -1; i < 20; i++) when you want to loop 20 times.
function testFunction() {
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = 0; i <= 20; i++) {
if (i % 5 == 0 && i % 3 == 0) {
myHTML += '<span class="test">Pineapple</span><br/>';
} else if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br/>';
} else if (i % 3 == 0) {
myHTML += '<span class="test">Pine</span><br/>';
} else {
myHTML += '<span class="test">' + i + '</span><br/>';
}
}
wrapper.innerHTML = myHTML
}
Using this code I was able to replace 5 with Apple.
function testFunction() {
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = -1; i < 20; i++){
if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br>';
} else{
myHTML += '<span class="test">' + i + '</span><br>'
}
}
wrapper.innerHTML = myHTML
}
testFunction();
<div id="Test"></div>
Use this snippet to follow what exactly happens within your loop. It should give you some clues.
const log = Logger();
testFunction();
function testFunction() {
for (let i = -1; i < 20; i += 1) {
if (i % 5 == 0 && i % 3 == 0) {
log(`${i} % 5 === 0 && ${i} % 3 === 0 => Pineapple`);
} else if (i % 5 == 0) {
log(`${i} % 5 === 0 => Apple` );
} else if (i % 3 == 0) {
log(`${i} % 3 === 0 => Pine`);
} else {
log(`i = ${i}, i + 1 = ${i + 1}`);
}
}
}
function Logger() {
let logEl;
if (typeof window === "object") {
logEl = document.querySelector("#log") || (() => {
document.body.appendChild(Object.assign( document.createElement('pre'), { id: "log" }) );
return document.querySelector("#log");
})();
return (...logLines) => logLines.forEach(s => logEl.textContent += `${s}\n`);
} else {
return (...logLines) => logLines.forEach(ll => console.log(`* `, ll));
}
}
Related
Is it possible to have the tables inside this snippet to be styled dynamically? Instead of splitting the data fetched each time and hardcoding it? They have different number of columns and rows. I'd like them to have the same style using only one split(), so I can have my code DRY. The approach to the solution would be on a complete different way than my code is written now? Thank you very much for the help.
function loadMountsVehicles() {
fetch('https://api.open5e.com/sections/mounts-and-vehicles/'
).then(function (responses) {
return responses.json();
}).then(function (data) {
displayMountsVehicles(data);
});
};
function displayMountsVehicles(data) {
let html = "";
html += `<h3>Mounts and Vehicles</h3>`;
for (let i = 0; i < data.desc.split(/\n/).length; i++) {
if (i < 16) {
html += `<p>${data.desc.split(/\n/)[i]}</p>`;
}
};
let mountsTable = data.desc.split(/[\n|]+/).splice(8, 40);
let index = mountsTable.indexOf("----------------");
if (index > -1) {
mountsTable.splice(index, 4);
};
let perrow = 4;
html += "<table><thead><tr>";
for (let i = 0; i < mountsTable.length; i++) {
html += `<td>${mountsTable[i]}</td>`;
let next = i + 1;
if (i === 3) {
html += `</thead>`;
} else if (next % perrow == 0 && next != mountsTable.length) {
html += "</tr><tr>";
}
};
html += "</tr></table>";
for (let i = 0; i < data.desc.split(/\n/).length; i++) {
if (i < 28 && i > 25) {
html += `<p>${data.desc.split(/\n/)[i]}</p>`;
}
};
let tackTable = data.desc.split(/[\n|]+/).splice(49, 51);
let indexTack = tackTable.indexOf("--------------------");
if (indexTack > -1) {
tackTable.splice(indexTack, 3);
};
let perrowTack = 3;
html += "<table><thead><tr>";
for (let i = 0; i < tackTable.length; i++) {
html += `<td>${tackTable[i]}</td>`;
let next = i + 1;
if (i === 2) {
html += `</thead>`;
} else if (next % perrowTack == 0 && next != tackTable.length) {
html += "</tr><tr>";
}
};
html += "</tr></table>";
for (let i = 0; i < data.desc.split(/\n/).length; i++) {
if (i > 45 && i < 49) {
html += `<p>${data.desc.split(/\n/)[i]}</p>`;
}
};
let waterboneTable = data.desc.split(/[\n|]+/).splice(101);
let indexWaterbone = waterboneTable.indexOf("--------------");
if (indexWaterbone > -1) {
waterboneTable.splice(indexWaterbone, 3);
};
let perrowWaterbone = 3;
html += "<table><thead><tr>";
for (let i = 0; i < waterboneTable.length; i++) {
html += `<td>${waterboneTable[i]}</td>`;
let next = i + 1;
if (i === 2) {
html += `</thead>`;
} else if (next % perrowWaterbone == 0 && next != waterboneTable.length) {
html += "</tr><tr>";
}
};
html += "</tr></table>";
html = html.replace(/\*\*\_([\w\(\)][\s\w\,\(\)\.]+)\_\*\*/g, "<span>$1</span>");
html = html.replace(/\*\*([\w\(\)\_][\s\w\,\(\)\_\.]+)\*\*/g, "<span>$1</span>");
document.querySelector(".content-text").innerHTML = html;
};
<body onload="loadMountsVehicles()">
<div class="content-text"></div>
</body>
This is the data returned from the API:
function loadMountsVehicles() {
fetch('https://api.open5e.com/sections/mounts-and-vehicles/'
).then(function (responses) {
return responses.json();
}).then(function (data) {
console.log(data.desc)
});
};
<body onload="loadMountsVehicles()">
</body>
function calculateBinary(bits) {
var bitValue = 0;
for(var i=0; i<bits.length; i++) {
if(bits[0] === '1') {
bitValue += 128;
} else if (bits[1] === '1') {
bitValue += 64;
} else if (bits[2] === '1') {
bitValue += 32;
} else if (bits[3] === '1') {
bitValue += 16;
} else if (bits[4] === '1') {
bitValue += 8;
} else if (bits[5] === '1') {
bitValue += 4;
} else if (bits[6] === '1') {
bitValue += 2;
} else if (bits[7] === '1') {
bitValue += 1;
}
}
return bitValue;
}
calculateBinary('11111111');
// Should return 255 (128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)
Why is my for loop treating every iteration of the bits string as bits[0]? The returned value is '1028' or 12 * 8. What am I doing wrong to cause this in my For loop?
Consider
for(var i=0; i<bits.length; i++) {
if(bits[0] === '1') {
bitValue += 128;
} else if
You aren't checking the index inside the loop - you're always checking bits[0], and then if that condition doesn't succeed, you're going onto bits[1], etc, without regard to the index.
Remove the loop.
function calculateBinary(bits) {
var bitValue = 0;
if (bits[0] === '1') {
bitValue += 128;
}
if (bits[1] === '1') {
bitValue += 64;
}
if (bits[2] === '1') {
bitValue += 32;
}
if (bits[3] === '1') {
bitValue += 16;
}
if (bits[4] === '1') {
bitValue += 8;
}
if (bits[5] === '1') {
bitValue += 4;
}
if (bits[6] === '1') {
bitValue += 2;
}
if (bits[7] === '1') {
bitValue += 1;
}
return bitValue;
}
console.log(calculateBinary('11111111'));
// Should return 255 (128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)
Or use the index inside the loop to calculate the amount to add.
function calculateBinary(bits) {
return [...bits].reverse().reduce(
(a, bit, i) => bit === '0' ? a : a + 2 ** i,
0
);
}
console.log(calculateBinary('11111111'));
console.log(calculateBinary('1000'));
(or, even better, don't reinvent the wheel)
Someone please help what is wrong in the following code. It is saying "Unexpected token else" while validating javascript code on Java Validate website - esprima.org
`
function add1()
{
var size = 8;
var widthOfGrid = size;
var lenthOfGrid = size;
var linenumber = 1;
for (i = 1 ; i<=size ; i += 1 )
{
for (j = 1 ; j<=size ; j += 1)
{
If (i % 2 === 0)
{
console.log(" " + "#");
}
else
{
console.log("#" + " ");
}
}
}
}
`
In Javascript there is no If statement. Javascript is a case-sensitive language Write it in the lower case - if. And also refactor your code, you have some unused variables.
The problem is that If should be lowercase.
The code should be like this:
function add1() {
var size = 8;
var widthOfGrid = size;
var lenthOfGrid = size;
var linenumber = 1;
for (i = 1; i <= size; i += 1) {
for (j = 1; j <= size; j += 1) {
if(i % 2 === 0)
{
console.log(" " + "#");
}
else
{
console.log("#" + " ");
}
}
}
}
function add1()
{
var size = 8;
var widthOfGrid = size;
var lenthOfGrid = size;
var linenumber = 1;
for (i = 1 ; i<=size ; i += 1 )
{
for (j = 1 ; j<=size ; j += 1)
{
if (i % 2 === 0)
{
console.log(" " + "#");
}
else
{
console.log("#" + " ");
}
}
}
}
working code,you forget make your if in lowercase
I am trying to get javascript to format phone numbers based on a users input of 10 or 11 digits. The 11 digits are for phone numbers that start with a 1 at the beginning like a 1-800 number. I need the final output to be either 000-000-0000 or 1-000-000-0000. The sample javascript code that I was given to start out with, works with the 10 digit phone number but I need the javascript to also recognize if there is a 1800 number and append accordingly.
The following is my initial working javascript and below that is code I found online that addresses the 10 and 11 digital formatting however I don’t know how to mesh the two together.
Thank you in advance for any help given.
~~~~~~~~~~~~~~~~~
<script type="text/javascript">
var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ];
InitialFormatTelephone();
function InitialFormatTelephone()
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
FormatTelephone(phoneNumberVars[i]);
}
}
function StorefrontEvaluateFieldsHook(field)
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]])
{
FormatTelephone(phoneNumberVars[i]);
}
}
}
function FormatTelephone(varName)
{
var num = document.getElementById("FIELD_" + FieldIDs[varName]).value;
var charArray = num.split("");
var digitCounter = 0;
var formattedNum;
if (charArray.length > 0)
formattedNum = “-“;
else
formattedNum = "";
var i;
for (i = 0;i < charArray.length; i++)
{
if (isDigit(charArray[i]))
{
formattedNum = formattedNum + charArray[i];
digitCounter++;
if (digitCounter == 3)
{
formattedNum = formattedNum + “-“;
}
if (digitCounter == 6)
{
formattedNum = formattedNum + "-";
}
}
}
if (digitCounter != 0 && digitCounter != 10)
{
alert ("Enter a valid phone number!");
}
// now that we have a formatted version of the user's phone number, replace the field with this new value
document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum;
// force an update of the preview
PFSF_AjaxUpdateForm();
}
function isDigit(aChar)
{
myCharCode = aChar.charCodeAt(0);
if((myCharCode > 47) && (myCharCode < 58))
{
return true;
}
return false;
}
</script>
<script type="text/javascript">
var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ];
InitialFormatTelephone();
function InitialFormatTelephone()
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
FormatTelephone(phoneNumberVars[i]);
}
}
function StorefrontEvaluateFieldsHook(field)
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]])
{
FormatTelephone(phoneNumberVars[i]);
}
}
}
function FormatTelephone(varName)
{
var num = document.getElementById("FIELD_" + FieldIDs[varName]).value;
var cleanednum = num.replace( /[^0-9]/g, "");
var charArray = cleanednum.split("");
var digitCounter = 0;
var formattedNum = "";
var digitPos1 = 0;
var digitPos3 = 3;
var digitPos6 = 6;
if (charArray.length ===11)
{
digitPos1++;
digitPos3++;
digitPos6++;
}
if (charArray.length > 0)
formattedNum = "";
else
formattedNum = "";
var i;
for (i = 0;i < charArray.length; i++)
{
if (isDigit(charArray[i]))
{
formattedNum = formattedNum + charArray[i];
digitCounter++;
if (digitCounter === digitPos1)
{
formattedNum = formattedNum + "-";
}
if (digitCounter == digitPos3)
{
formattedNum = formattedNum + "-";
}
if (digitCounter == digitPos6)
{
formattedNum = formattedNum + "-";
}
}
}
if ((charArray.length ==10 || charArray.length == 11 || charArray.length == 0) === false)
{
alert ("Enter a valid phone number!");
}
// now that we have a formatted version of the user's phone number, replace the field with this new value
document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum;
// force an update of the preview
PFSF_AjaxUpdateForm();
}
function isDigit(aChar)
{
myCharCode = aChar.charCodeAt(0);
if((myCharCode > 47) && (myCharCode < 58))
{
return true;
}
return false;
}
</script>
How can I remove the last comma from this function.
for(var i = 0; i <= 100; i++) {
if(i % 2 === 0) {
div.innerHTML += l + ",";
}
else {
div.innerHTML += " ";
}
}
First, use arrays instead strings for sum strings, its faster.
Second:
var arr = [];
for (var i = 0 ;i <= 100; i+=2) arr.push(l);
dividedThree.innerHTML = arr.join(', ');
function loop {
for (var i = 0; i <= 100; i++) {
if (i % 2 === 0) {
dividedThree.innerHTML += l;
if (i < 100)
{
dividedThree.innerHTML += ",";
}
} else {
dividedThree.innerHTML += " ";
}
}
}
Try using and (&&) condition for 100 and show only i value for 100.
function loop() {
var dividedThree = document.getElementById('MY_ID');
for (var i = 0; i <= 100; i++) {
if (i % 2 === 0 && i !== 100) {
dividedThree.innerHTML += i + ", ";
} else if (i === 100) {
dividedThree.innerHTML += i;
} else {
dividedThree.innerHTML += " ";
}
}
}
loop();
<p id="MY_ID">
<p>
does this version work for you?
function loop() {
var data = '';
for (var i = 0; i <= 49; i++) {
data += l + ',' + ' ';
}
data += l;
dividedThree.innerHTML = data;
}
What are you trying to do? where does 'l' come from?