Search code examples
javascripthtmlrot13

JS won't link to HTML button


I have a Rot13 JS function that I am attempting to link to a button. The expected output is meant to be that if I enter 'ABC' and press the Encrypt button, the encrypted text becomes 'NOP'.

The function doesn't currently link up to the buttons in HTML and when I press the encrypt button there is no response. I've included a script tag in the HTML.

EDIT: the encrypter is linked to the button, however it encrypts 'ABC' to 'ABC.

JavaScript:

function rot13() {
  var input = document.getElementById("box1").value;
  var output = [];

  for (var i = 0; i < input.length; i++) {
    var asciiNum = input[i].charCodeAt();
    if (asciiNum >= 65 && asciiNum <= 77) {
      output.push(String.fromCharCode(asciiNum + 13))
    } else if (asciiNum >= 78 && asciiNum <= 90) {
      output.push(String.fromCharCode(asciiNum - 13))
    } else {
      output.push(input[i])
    }
  }
  document.getElementById("box2").value = output.join('');
}
<div class="form">
        <input type="text" placeholder="plain text here..." name="plaintext" id="box1">
        <br>
        <button type="button" onclick="rot13()">Encrypt</button>
        <button type="button" onclick="rot13()">Decrypt</button>
        <br>
        <input type="text" placeholder="encrypted message here..." name="encryptedtext" id="box2">
      </div>

EDIT: corrected the JS.


Solution

  • There are few problems with code:

    • output.join('') = document.getElementById("box2") will throw error. You should set .value to output.join(''). The left hand side of = should be a variable. output.join('') returns are value and it cannot be assigned to anything.
    • output + input[i] will do nothing. You should use push() to add values to array.

    function rot13() {
      var input = document.getElementById("box1").value;
      var output = [];
    
      for (var i = 0; i < input.length; i++) {
        var asciiNum = input[i].charCodeAt();
        if (asciiNum >= 65 && asciiNum <= 77) {
          output.push(String.fromCharCode(asciiNum + 13))
        } else if (asciiNum >= 78 && asciiNum <= 90) {
          output.push(String.fromCharCode(asciiNum - 13))
        } else {
          output.push(input[i])
        }
      }
      document.getElementById("box2").value = output.join('');
    }
    <div class="form">
            <input type="text" placeholder="plain text here..." name="plaintext" id="box1">
            <br>
            <button type="button" onclick="rot13()">Encrypt</button>
            <button type="button" onclick="rot13()">Decrypt</button>
            <br>
            <input type="text" placeholder="encrypted message here..." name="encryptedtext" id="box2">
          </div>