I'm trying to make a simple encrypting system. I made a code with all letters but when I write text and click the button to encrypt it just recognizes one letter.
HTML:
<input type="text" id="text">
<input type="button" id="send" onclick="onClick()" value="encript">
<a id="itext">Your text will show here</a>
<a type="text" id="code">Your encrypted text will be showed here</a>
JS:
function onClick() {
var txt = document.getElementById("text").value;
document.getElementById("itext").innerHTML = txt;
if(txt == "a"){
document.getElementById("code").innerHTML = "yv";
}
if(txt == "b"){
document.getElementById("code").innerHTML = "eh";
}
if(txt == "c"){
document.getElementById("code").innerHTML = "ps";
}
...
}
The problem is that you're checking the entirety of the string against single letters. You should split the string into characters and iterate over each of them. Something like this:
function onClick() {
var txt = document.getElementById("text").value;
document.getElementById("itext").innerHTML = txt;
var letters = txt.split('')
var new_string = ''
var i = 0;
for(i = 0; i < letters.length; i++){
if(letters[i] == "a"){
new_string = new_string + "yv";
}
if(letters[i] == "b"){
new_string = new_string + "eh";
}
if(letters[i] == "c"){
new_string = new_string + "ps";
}
...
}
document.getElementById("code").innerHTML = new_string;
}
You could also build a function that catches your keyboard input like this:
document.addEventListener('keydown', function(event) {
if(event.keyCode == 65) {
var code = document.getElementById("code");
code.appendChild(document.createTextNode("yv"));
}
else if(event.keyCode == 66) {
var code = document.getElementById("code");
code.appendChild(document.createTextNode("eh"));
}
else if(event.keyCode == 67) {
var code = document.getElementById("code");
code.appendChild(document.createTextNode("ps"));
}
});
i have made an example here: https://jsbin.com/bohucecudu/edit?html,output
If you got this, then you don't need to click first on the button to get results :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.