1

I have a javascript variable with parameters, but I don't know how to pass it into my html code. The javascript code is taken from https://gist.github.com/EvanHahn/2587465:

var caesarShift = function(str, amount) {

    // Wrap the amount
    if (amount < 0)
        return caesarShift(str, amount + 26);

    // Make an output variable
    var output = '';

    // Go through each character
    for (var i = 0; i < str.length; i ++) {

        // Get the character we'll be appending
        var c = str[i];

        // If it's a letter...
        if (c.match(/[a-z]/i)) {

            // Get its code
            var code = str.charCodeAt(i);

            // Uppercase letters
            if ((code >= 65) && (code <= 90))
                c = String.fromCharCode(((code - 65 + amount) % 26) + 65);

            // Lowercase letters
            else if ((code >= 97) && (code <= 122))
                c = String.fromCharCode(((code - 97 + amount) % 26) + 97);

        }

        // Append
        output += c;

    }

    // All done!
    return output;

};

I want to pass it on to my HTML obviously. I have done some research, and have come across ways such as:

<p id="output"></p>

and then

document.getElementById('output').innerHTML = lengthOfName;

but I don't know how to add it all together. How do I call the variable? For the string, I have a text area input box, and maybe a clicker for the second argument, the amount, but I don't know how to put it all together in the HTML.

PythonicOreo
  • 422
  • 1
  • 4
  • 14

1 Answers1

1

You'll need to up the JavaScript inside a script tag and the p tag that you are getting by id in the body of an html document, like so:

<!DOCTYPE html>

<html>
  <head>
    <title>Page</title>
  </head>

  <body>
    <form id="form">
      <div>
        <label for="str">String:</label>
        <input id="str" />
      </div>
      <div>
        <label for="amount">Amount:</label>
        <input id="amount" />
      </div>
      <button type="submit">Submit</button>
    </form>
    <p>CaesarShift: <span id="output"></span></p>

    <script>
      var caesarShift = function (str, amount) {
        // Wrap the amount
        if (amount < 0) return caesarShift(str, amount + 26);

        // Make an output variable
        var output = "";

        // Go through each character
        for (var i = 0; i < str.length; i++) {
          // Get the character we'll be appending
          var c = str[i];

          // If it's a letter...
          if (c.match(/[a-z]/i)) {
            // Get its code
            var code = str.charCodeAt(i);

            // Uppercase letters
            if (code >= 65 && code <= 90)
              c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
            // Lowercase letters
            else if (code >= 97 && code <= 122)
              c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
          }

          // Append
          output += c;
        }

        // All done!
        return output;
      };

      const form = document.getElementById("form");
      form.addEventListener("submit", handleSubmit);

      function handleSubmit(event) {
        event.preventDefault();
        let str = document.getElementById("str").value;
        let amount = parseInt(document.getElementById("amount").value);
        let output = document.getElementById("output");
        console.log(amount);
        if (!amount) {
          output.innerHTML = `<span style="color: red">Amount not valid</span>`;
          return;
        }
        output.innerHTML = caesarShift(str, parseInt(amount));
      }
    </script>
  </body>
</html>

See the snippet below with a working example:

var caesarShift = function(str, amount) {
  // Wrap the amount
  if (amount < 0) return caesarShift(str, amount + 26);

  // Make an output variable
  var output = "";

  // Go through each character
  for (var i = 0; i < str.length; i++) {
    // Get the character we'll be appending
    var c = str[i];

    // If it's a letter...
    if (c.match(/[a-z]/i)) {
      // Get its code
      var code = str.charCodeAt(i);

      // Uppercase letters
      if (code >= 65 && code <= 90)
        c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
      // Lowercase letters
      else if (code >= 97 && code <= 122)
        c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
    }

    // Append
    output += c;
  }

  // All done!
  return output;
};

const handleSubmit = (e) => e.preventDefault();

const updateResult = () => {
  amount = parseInt(document.getElementById("amount").value);
  let output = document.getElementById("output");
  if (!amount) {
    output.innerHTML = `<span style="color: red">Amount not valid</span>`;
    return;
  }
  output.innerHTML = caesarShift(
    document.getElementById("text").value,
    parseInt(amount)
  );
};

const form = document.getElementById("form");
form.addEventListener("submit", handleSubmit);

let text = document.getElementById("text");
text.addEventListener("keyup", updateResult);
text.addEventListener("blur", updateResult);

let amount = document.getElementById("amount");
amount.addEventListener("change", updateResult);
amount.addEventListener("blur", updateResult);
<form id="form">
  <div>
    <label for="text">Text:</label>
    <textarea id="text"></textarea>
  </div>
  <div>
    <label for="amount">Amount:</label>
    <input id="amount" />
  </div>
</form>
<p>CaesarShift: <span id="output"></span></p>
Luís Ramalho
  • 10,018
  • 4
  • 52
  • 67
  • Any explanation to provide? What exactly did you do or change? How is this code working? – Jeremy Thille Apr 08 '20 at 06:01
  • Thank you! I don't know how I didn't see that. But is there a way for the string and shift number to be user input? – PythonicOreo Apr 08 '20 at 06:03
  • Yes, you'll need to add `input` fields and then grab their values. You can try on your own based on my example above and then if not able you can open another question by sharing what you've tried. – Luís Ramalho Apr 08 '20 at 06:05
  • that's what question was asking for. I'm not sure how to ask for the string and shift number with javascript, and not doing something like submitting a form. – PythonicOreo Apr 08 '20 at 06:35
  • @PythonicOreo, I've updated my answer to achieve what you're looking for. If that was helpful please consider accepting it :) -- I've also added a rudimentary check to see if the amount is a number or not. Please let me know if you have any further questions. You can click "Run code snippet" to test the code. Also, have a look at https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event -- that should help you understand what is happening. – Luís Ramalho Apr 08 '20 at 07:13
  • @LuísRamalho, at this point I should add a new question, but the thing is I would like to have it live. The reason is because I'm trying to create a site that has a lot of ways to decrypt 1 string. So if the user has to click submit every time, especially 25 times in this case, that's not going to be that helpful. Is there any way to make it live without a submit button? This is what I'm kind of going for, https://cryptii.com/pipes/caesar-cipher. – PythonicOreo Apr 08 '20 at 18:36
  • @PythonicOreo, I've updated my answer one last time. StackOverflow is not a code writing service, so you'll need to try on your own and then come with a specific question and not a feature request :) -- having said that, what you need in that case is some kind of event listener to listen to those event, I've used [`blur`](https://developer.mozilla.org/en-US/docs/Web/API/Element/blur_event) and [`keyup`](https://developer.mozilla.org/en-US/docs/Web/API/Document/keyup_event) but others could work too, then you just update the result. Glad I was able to help you and good luck with your project! – Luís Ramalho Apr 08 '20 at 21:38
  • Well actually that was my question in the first place; it seems as if you didn't understand my question. Next time I'll try to my question's clearer. – PythonicOreo Apr 08 '20 at 22:29