merrybot
merrybot

Reputation: 155

JS Encryption w/ HTML

This should add the encoded text to the HTML but doesn't seem to work.

<script>
var i=0,j=0,k=0;
var letters=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
function gibberish(string, list) {
document.innerHTML +="<p>";
for(var j=0;j<string.length;j++){
document.innerHTML += letters[(letters.indexOf(string.charAt(k))*list[(j%8)]+list[((j+1)%8)])%8];
k++;
}
document.innerHTML += "</p>";
}
var array = [];
var ptxt;
for(i=1;i<9;i++) {
array.push(prompt("enter a number (less than 10 preferably!)"));
}
ptxt = prompt("ok now enter a string");
gibberish(ptxt,array);
</script>

What am I doing incorrectly, et cetera?

Upvotes: 3

Views: 79

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370589

The document does not have an innerHTML property. You have to select an element inside it - perhaps the document.body. You also shouldn't concatenate unbalanced tags - concatenate a balanced HTML string all at once, when it's ready:

var i = 0,
  j = 0,
  k = 0;
var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

function gibberish(string, list) {
  let str = "<p>";
  for (var j = 0; j < string.length; j++) {
    str += letters[(letters.indexOf(string.charAt(k)) * list[(j % 8)] + list[((j + 1) % 8)]) % 8];
    k++;
  }
  document.body.innerHTML += str + "</p>";
}
var array = [];
var ptxt;
for (i = 1; i < 9; i++) {
  array.push(prompt("enter a number (less than 10 preferably!)"));
}
ptxt = prompt("ok now enter a string");
gibberish(ptxt, array);

But concatenating with the innerHTML of an element is usually a bad idea - it'll force the whole container to be re-parsed, and will corrupt any listeners the container may have inside it. To avoid those problems, it might be better to create a <p> and use appendChild instead.

You can also create the letters array less repetitively by iterating over key codes.

It would also be good to make sure that the inputted numbers are actually numbers - you can use a do-while loop to verify them:

const letters = Array.from({ length: 26 }, (_, i) => String.fromCharCode(97 + i));
function gibberish(string, list) {
  let k = 0;
  const p = document.createElement('p');
  for (let j = 0; j < string.length; j++) {
    p.textContent += letters[(letters.indexOf(string.charAt(k)) * list[(j % 8)] + list[((j + 1) % 8)]) % 8];
    k++;
  }
  document.body.appendChild(p);
}
var array = [];
for (let i = 1; i < 9; i++) {
  let num = null;
  do {
    prompt("enter a number (less than 10 preferably!)");
  } while (num === null);
  array.push(num);
}
gibberish(prompt("ok now enter a string"), array);

Upvotes: 2

Yosef Tukachinsky
Yosef Tukachinsky

Reputation: 5895

document not have innerHTML property. try to use document.body.innerHTML

Upvotes: 1

Related Questions