Skip to content
Advertisement

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>
<br>
<textarea name="text" id="text_encode" style="width: 30%;height: 200px"> 
</textarea>
<br>
<br>

<label for="methods">Select your methods : </label>
<br>
<br>
<select name="methods" id="methods">

  <option value="Caesar">Caesar</option>


</select>
<br>
<br>
<input type="button" value="Encrypt" onClick=encryption()>


<br>
<br>
<textarea name="text" id="text_decoded" style="width: 30%;height: 200px" 
readonly="readonly"></textarea>
</form>

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;
        }
        document.getElementById("text_decoded").value=output;
        break;
    }
}

You can also go here if you want to test what’s wrong directly: https://www.w3schools.com/code/tryit.asp?filename=FXJU1NAG37C0

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement