Skip to content

Problem with caesar cipher shift javascript

For a school project, I’m trying to create a website on encryption methods, but right now I have a problem with my Caesar one. I checked so many times but I can’t find out where is the problem in my code. I think the shift is what is wrong, but I don’t know what I could change to make it work, and I would be very happy if someone could help me.

So, here is the html part :

<form name="formu" action="">
<label for="pseudo">Your text :</label>
<textarea name="text" id="text_encode" style="width: 30%;height: 200px">
<label for="methods">Select your methods : </label>
<select name="methods" id="methods">
  <option value="Caesar">Caesar</option>
<input type="button" value="Encrypt" onClick=encryption()>
<textarea name="text" id="text_decoded" style="width: 30%;height: 200px"

And here is my javascript code:

function encryption() {
switch(document.getElementById("methods").value) {
    case "Caesar":
        var str = document.getElementById("text_encode").value;
        var amount = prompt("Number of shift");
        var output = "";
        for (var i = 0; i < str.length; i ++) {
            var c = str[i];
            var code = str.charCodeAt(i);
            if ((code >= 65) && (code <= 90))
                c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
            else if ( (code >= 97) && (code <= 122) )
                c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
            output += c;

You can also go here if you want to test what’s wrong directly:


The mistake is this line:

var amount = prompt("Number of shift");

This by default returns a string, but it may contain a number – so if I enter 10 in the prompt box, amount will be:

amount = "10"

To fix this, you need to parse the string into an integer:

var amount = Number(prompt("Number of shift"));

Then your code should work.