Making custom encryption with javascript (stuck in decrypt function) - javascript

I want to make new custom encryption engine with javascript, but i have a problem when i make a decryption function. In my decryption function I don't understand how to switch 3 characters to 1 character. In the decryption function section, 3 characters from the case I do not want are changing to the characters that are returned.
If you need my full code, i can share in here.
So please help me to solve this problem. Sorry for my bad English :)
<body>
<h3>Encrypt and Decrypt</h3>
<!-- Encrypt -->
<!-- <input placeholder="Ketikan sesuatu disini, pasti bisa:v" id="input"><br>
<button onclick="encrypt()">Encrypt</button> -->
<!-- Decrypt -->
<br><input placeholder="Ketikan sesuatu disini, pasti bisa:v" id="input2"><br>
<button onclick="decrypt()">Decrypt</button>
<!-- Result -->
<div id="result"></div>
<!-- Enginenya -->
<script>
function encrypt(){
var rawtext = document.getElementById("input").value;
var temptext = "";
for(i = 0; i < rawtext.length; i++){
temptext += enc(rawtext[i]);
}
document.getElementById("result").innerHTML = temptext;
}
function decrypt(){
var rawtext = document.getElementById("input2").value;
var temptext = "";
for(i = 0; i < rawtext.length; i++){
temptext += dec(rawtext[i]);
}
document.getElementById("result").innerHTML = temptext;
}
function enc(x){
switch(x){
case " " :
return " ";
break;
case "A" :
return "+/=";
break;
case "B" :
return "36=";
break;
}
}
function dec(x){
switch(x){
case "+/=" :
return "A";
break;
case "36=" :
return "B";
break;
}
}
</script>
</body>

You are looping through singular chars & passing them to dec(), eg. If you enter "+/=", you are actually calling dec('+') then dec('/') then dec('=')
When decrypting the entered value, you'll have to split them into groups of 3 & then pass those.
function decrypt(){
var rawtext = document.getElementById("input2").value;
var temptext = "";
for(i = 0, charsLength = rawtext.length; i < charsLength; i += 3){
temptext += dec(rawtext.substring(i, i + 3));
}
document.getElementById("result").innerHTML = temptext;
}

You could take three caracters for decrypting an encrypted string.
while (i < rawtext.length) {
temptext += dec(rawtext.slice(i, i += 3)); // take from index i and increment i by 3
}
function encrypt() {
var rawtext = document.getElementById("input").value,
temptext = "",
i;
for (i = 0; i < rawtext.length; i++) {
temptext += enc(rawtext[i]);
}
document.getElementById("result").innerHTML = temptext;
}
function decrypt() {
var rawtext = document.getElementById("input2").value,
temptext = "",
i = 0;
while (i < rawtext.length) {
temptext += dec(rawtext.slice(i, i += 3));
}
document.getElementById("result").innerHTML = temptext;
}
function enc(x) {
switch (x) {
case " ":
return " ";
case "A":
return "+/=";
case "B":
return "36=";
}
}
function dec(x) {
switch (x) {
case "+/=":
return "A";
case "36=":
return "B";
}
}
<h3>Encrypt and Decrypt</h3>
<input placeholder="Ketikan sesuatu disini, pasti bisa:v" id="input"><br>
<button onclick="encrypt()">Encrypt</button>
<!-- Decrypt -->
<br><input placeholder="Ketikan sesuatu disini, pasti bisa:v" id="input2"><br>
<button onclick="decrypt()">Decrypt</button>
<!-- Result -->
<div id="result"></div>

Looks like you're iterating over the text to decrypt character by character, but then your dec function expects three characters. This never happens, so dec() returns undefined.
Example:
decrypt("36=") ->
dec("3") + dec("6") + dec("=") ->
undefined + undefined + undefined
undefinedundefinedundefined
You should change your decrypt function to avoid this. Additionally, some pointers:
You don't initialise i in your encrypt/decrypt function
There's no need for a break; after a return in your case statements as return will end the execution.
Edit: Here's an example with map since some other answers had some with for loops. And also because I suspected it could be done with one line (and I was right!)
<body>
<h3>Encrypt and Decrypt</h3>
<br><input placeholder="Ketikan sesuatu disini, pasti bisa:v" id="input2"><br>
<button onclick="decrypt()">Decrypt</button>
<div id="result"></div>
<script>
function decrypt(){
document.getElementById("result").innerHTML = document.getElementById("input2").value.match(/.{1,3}/g).map(dec).join('');
}
function dec(x){
switch(x){
case "+/=" :
return "A";
case "36=" :
return "B";
default:
return "?";
}
}
</script>
</body>

Related

How to find if there is a space in a string... tricky

I'm doing this for a school project but one thing is bugging me, there is a part of the project that requires me to change white space or just " " a space to a number. Here is my code:
I know its messy, I've only been coding for half a year
exclsp is "exclude spaces"
inclsp is "include spaces"
dispwos is "display without spaces"
dispwsp is "display with spaces"
var txt;
var num;
var spce = 0;
function cnt()
{
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked === true)
{
for (var i = 0; i < num; i++) {
if (txt.includes(" "))
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
}
}
document.getElementById("dispwos").innerHTML = num - spce + " characters.";
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="LetterCount.js"></script>
<link rel="stylesheet" type="text/css" href="LetterCount.css"/>
<title>Letter Counter</title>
</head>
<body>
<textarea rows="4" cols="50" placeholder="Input your text here!" id="disp"></textarea><br>
<form name="form1">
<input type="radio" name="button" id="inclsp"> Include spaces</input><br>
<input type="radio" name="button" id="exclsp"> Exclude spaces</input><br>
</form>
<button onclick="cnt()">Click Me!</button><br><br>
<div id="dispwsp"></div>
<div id="dispwos"></div>
</body>
</html>
I think you need to change this line:
if (txt.includes(" "))
to
if (txt[i] == " ")
so that you're actually checking each character rather that attempting to examine the whole string each time.
You could also use a regular expression and do it in one simple line of code and eliminate the loop altogether:
spce = txt.match(/\s/g).length
I don't understand the purpose of the dispwsp dispwos so I just removed them. You only have 1 result you want to display so why put it in different places just make one div for your result, like
<div id="result"></div>
And your JS can be simplified a lot, you don't need to loop through the letters. Here's the fiddle: https://jsfiddle.net/zwzqmd27/
function cnt() {
var inputText = document.getElementById("disp").value;
if (document.getElementById("exclsp").checked) //exclude spaces
{
document.getElementById("result").innerHTML = inputText.split(" ").join("").length + " characters";
}
else //include spaces
{
document.getElementById("result").innerHTML = inputText.length + " characters";
}
}
Possible duplicate of Check if a string has white space
But you can try this.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
If You want to change a white space in a string to a number..
This could possibly help you ...
str.replace(/\s/g,"9");//any number(that You want)
This piece of code is basically replaces the white space with a number..
As #Micheal said, you can use indexOf() method to check if particular character(s) is present in your text content.
You just need to pass the character or substring(set of characters) to check if it is present.
Example :
var myText = "Sample text";
var substringIndex = myText.indexof(" "); //substringIndex = 6
substringIndex = mytext.indexof("ex");//substringIndex = 8;
substringIndex = mytext.indexof("tt"); // substringIndex =-1;
If substring doesn't matches, it will return -1 as index.
By using index you can say, if particular character(substring) presents if index value is greater than -1.
Note : If u pass set of characters, it will return only the starting index of the first character if entire set matches.
In your case, it would be like
...........
...........
if (txt.indexOf(" ")>-1)
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
...............
...............
Just replace script with code bellow..
I do it for you...
var txt;
var num;
var spce = 0;
function cnt()
{
//to clear "dispwsp" and "dispwos" before action in cnt() function
document.getElementById("dispwsp").innerHTML = "";
document.getElementById("dispwos").innerHTML = "";
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked == true)
{
num = 0;
spce = 0;
for (var i = 0; i < txt.length; i++) {
var temp = txt.substring(i, (i+1));
if(temp==" ")
{
spce++;
}else
{
num++;
}
document.getElementById("dispwos").innerHTML = num + " characters and "+ spce +" spces ";
}
}
}

Reset Function for dice rolling game

I have worked for a while on this code for learning purposes. I finally got the program to work, however when you "roll the dice", it only allows the dice to be rolled 1 time; If you wish to roll the dice a second time you must refresh the screen.
I am trying to build a reset function for this program so that I can roll the dice as many times as I wish without a screen-refresh.
I have built the reset function, but It is not working... It clear's the DIV's, but doesn't allow the program to be executed again.
Can someone please help me out?
*I am a semi-noobie at Javascript, I am making programs like this to practice my skills.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dice Rolling</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header>
<h1>Roll the Dice!</h1>
<h2>By: Jeff Ward</h2>
</header>
<h3>Setup your Dice!</h3>
<div id="left">
<form id="numberOfDiceSelection">
Number Of Dice Used:
<br>
<input id="numberOfDice" type="text" name="numberOfDice">
</form>
</div>
<div id="right">
<form id="diceSidesSelection">
Number of sides on each dice:
<br>
<input id="diceSides" type="text" name="diceSides">
</form>
</div>
<button type="button" onclick="roll()">Roll the Dice!</button>
<button type="button" onclick="reset()">Reset Roll</button>
<div id="output">
</div>
<div id="output1">
</div>
<script src="js/script.js"></script>
</body>
</html>
JavaScript:
function roll() {
var text = "";
var sides = +document.getElementById("diceSides").value;
var dice = +document.getElementById("numberOfDice").value;
var rolls = [];
// --------Ensures both Numbers are Intergers-----------
if (isNaN(sides) || isNaN(dice)) {
alert("Both arguments must be numbers.");
}
// --------Loop to Print out Rolls-----------
var counter = 1;
do {
roll = Math.floor(Math.random() * sides) + 1;
text += "<h4>You rolled a " + roll + "! ----- with dice number " + counter + "</h4>";
counter++;
rolls.push(roll);
}
while (counter <= dice)
document.getElementById("output").innerHTML = text;
// --------Double Determination-----------
var cache = {};
var results = [];
for (var i = 0, len = rolls.length; i < len; i++) {
if (cache[rolls[i]] === true) {
results.push(rolls[i]);
} else {
cache[rolls[i]] = true;
}
// --------Print amount of Doubles to Document-----------
}
if (results.length === 0) {} else {
document.getElementById("output1").innerHTML = "<h5> You rolled " + results.length + " doubles</h5>";
}
}
// --------RESET FUNCTION-----------
function reset() {
document.getElementById("output1").innerHTML = "";
document.getElementById("output").innerHTML = "";
document.getElementById("diceSides").value = "";
document.getElementById("numberOfDice").value = "";
text = "";
rolls = [];
}
Thank you!!
JSFiddle Link = https://jsfiddle.net/kkc6tpxs/
I rewrote and did what you were trying to do:
https://jsfiddle.net/n8oesvoo/
var log = logger('output'),
rollBtn = getById('roll'),
resetBtn = getById('reset'),
nDices = getById('numofdices'),
nSides = getById('numofsides'),
dices = null,
sides = null,
rolls = [],
doubles=0;
rollBtn.addEventListener('click',rollHandler);
resetBtn.addEventListener('click', resetHandler);
function rollHandler() {
resetView();
sides = nSides.value;
dices = nDices.value;
doubles=0;
rolls=[];
if(validateInput()) {
log('invalid input');
return;
}
//rolling simulation
var rolled;
while (dices--) {
rolled = Math.ceil(Math.random()*sides);
log('For Dice #'+(dices+1)+' Your Rolled: '+ rolled +'!');
rolls.push(rolled);
}
//finding doubles
//first sort: you can use any way to sort doesnt matter
rolls.sort(function(a,b){
return (a>b?1:(a<b)?0:-1);
});
for (var i =0; i < rolls.length; i++) {
if (rolls[i] == rolls[i+1]) {
doubles++;
i++;
}
}
if (doubles>0) log("You rolled " + doubles + " doubles");
}
function resetHandler(){
resetView();
nDices.value = nSides.value = '';
}
function resetView() {
getById('output').innerText = '';
}
function validateInput(){
return (isNaN(sides) || sides == '' || isNaN(dices) || dices == '');
}
function logger(x) { var output = getById(x);
return function(text){
output.innerText += text + '\n';
};}
function getById(x){ return document.getElementById(x); }

How to add dynamic textbox in java script

I need to create text box using JavaScript. I coded as below:
<script>
function _(x) {
return document.getElementById(x);
}
function popuptxt() {
var i = _("no_room").value;
for(a = 1; a <= i; a++) {
my_div.innerHTML = my_div.innerHTML + "Room number for " + a + "<br><input type='text' name='mytext'+ i><br>"
}
}
<script>
HTML file:
<input type="text" style="width:200px;" id="no_room" onChange="popuptxt()" required>
<div id="my_div"></div>
It displays number of textbox when I type a number, but I need to clear them when I type another number.
Just reset the content of you block each time :
<script>
function _(x) {
return document.getElementById(x);
}
function popuptxt() {
my_div.innerHTML = "";
var i = _("no_room").value;
for(a = 1; a <= i; a++) {
my_div.innerHTML = my_div.innerHTML + "Room number for " + a + "<br><input type='text' name='mytext'+ i><br>"
}
}
</script>
Just add my_div.innerHTML = ""; before the for loop in popuptxt(). That way it will be cleared each time its called.

Function with if else statement - javascript

Could anyone please tell me what I'm doing wron here?
I'm sort of new to Javascript and I can't get this function to work the way i want it..
Basically if i type in ABCJ in the number1 field , i want to display 123X in the ansarea
<!DOCTYPE html>
<html>
<body>
<script>
function convert(number1)
{
for(var i=0;i<number1.length();i++)
{
if(number1[i]=='A')
{
document.getElementById("ansarea").innerHTML="1";
}
else if(number1[i]=='B')
{
document.getElementById("ansarea").innerHTML="2";
}
else if(number1[i]=='C')
{
document.getElementById("ansarea").innerHTML="3";
}
else if(number1[i]=='D')
{
document.getElementById("ansarea").innerHTML="4";
}
else if(number1[i]=='E')
{
document.getElementById("ansarea").innerHTML="5";
}
else
{
document.getElementById("ansarea").innerHTML="x";
}
}
}
</script>
<form>Enter here : <input type="text" name="number1"><br></form>
<button type="button" onclick="convert("number1")">Convert</button>
<div id="ansarea"><input type="text" name = "ans"></div>
</body>
</html>
this will make you code work...
<!DOCTYPE html>
<html>
<body>
<script>
function convert() {
var valu = document.getElementById("some").value;
document.getElementById("ansarea").innerHTML = "";
for (var i = 0; i < valu.length; i++) {
if (valu[i] == 'A') {
document.getElementById("ansarea").innerHTML += "1";
} else if (valu[i] == 'B') {
document.getElementById("ansarea").innerHTML += "2";
} else if (valu[i] == 'C') {
document.getElementById("ansarea").innerHTML += "3";
} else if (valu[i] == 'D') {
document.getElementById("ansarea").innerHTML += "4";
} else if (valu[i] == 'E') {
document.getElementById("ansarea").innerHTML += "5";
} else {
document.getElementById("ansarea").innerHTML += "x";
}
}
}
</script>
<form>Enter here : <input type="text" name="number1" id="some"><br>
<button type="button" onclick="convert()">Convert</button>
<div id="ansarea"></div>
</form>
</body>
</html>
you dont need to pass a value to convert() since you are getting the value from the input field, you dont need the other input field, since you putting the text in a div..
This is another working example:
<!DOCTYPE html>
<head>
<script>
function convert()
{
var number1 = document.getElementById('textbox_id').value;
for(var i=0;i<number1.length;i++)
{
if(number1.charAt(i)=='A')
{
document.getElementById("ansarea").innerHTML +="1";
}
else if(number1.charAt(i)=='B')
{
document.getElementById("ansarea").innerHTML +="2";
}
else if(number1.charAt(i)=='C')
{
document.getElementById("ansarea").innerHTML +="3";
}
else if(number1.charAt(i)=='D')
{
document.getElementById("ansarea").innerHTML +="4";
}
else if(number1.charAt(i)=='E')
{
document.getElementById("ansarea").innerHTML +="5";
}
else
{
document.getElementById("ansarea").innerHTML +="x";
}
}
}
</script>
</head>
<body>
Enter here : <input type="text" name="number1" id='textbox_id'>
</br>
<button type="button" onclick="convert()">Convert</button>
<div id="ansarea"></div>
</body>
</html>
Few things to notice here:
You can take the value from inside the function convert()
You don't need the second onpening <html> tag after <!DOCTYPE html>
It's better not to skip the <head> tag
For this task specifically you don't need <form> so I've removed it, but you can add it if you plan to submit to some other method or something...
First, welcome to javascript ! Because you are starting, a good rule of thumb to start is to find your way around repetitions.
Here's another example on how you can execute exactly the same thing as in the other answers using a map:
// let's map all the characters you need against some digits
// this will make it super easy to add, remove or swap things around.
var map = { A: '1', B: '2', C: '3', D: '4', E: 5 };
// for example, map['A'] will now have the value of '1'
// we can store the output element once for good,
// so you don't have to look it up over and over again.
var outputElement = document.getElementById('ansarea');
function convert( inputString ) {
// the result variable will temporary store the result, so let's start empty
var result = "";
for ( var i = 0; i < inputString.length; i ++ ) {
// grab the current character so we don't have to look it up twice
var char = inputString[i];
if ( typeof map[char] !== 'undefined' ) {
// cool, the character existed within the map.
// We can append its value to the result:
result += map[char];
} else {
// ... if not add 'x'
result += 'x';
}
}
// and finally, populate the HTML with the result
outputElement.innerHTML = result;
}
innerHTML - it is property containing html in element. And every time you completely rewriting it.
Try this:
document.getElementById("ansarea").innerHTML+="1";
document.getElementById("ansarea").innerHTML+="2"; // etc
By += (instead =) you will concatenate old value with new.
And you must change you function call.
Try this (i don't test it):
function convert(selector) {
var dataFromInput = document.querySelector(selector);
var dataLength = dataFromInput.length();
var ansarea = document.getElementById("ansarea");
for(var i = 0; i < dataLength; i++) {
switch (dataFromInput[i]) {
case 'A':
ansarea.innerHTML += '1';
break;
case 'B':
ansarea.innerHTML += '2';
break;
case 'C':
ansarea.innerHTML += '3';
break;
case 'D':
ansarea.innerHTML += '4';
break;
case 'E':
ansarea.innerHTML += '5';
break;
default:
ansarea.innerHTML += 'x';
}
}
}
and add id for input:
<form>Enter here : <input type="text" name="number1" id="number1"><br></form>
<button type="button" onclick="convert('#number1')">Convert</button>

Limiting character in textbox input

please be nice. I'm trying to create a page which sets limit and cut the excess (from the specified limit). Example: Limit is 3. then, I'll input abc if I input d it must say that its limit is reached and the abc will remain. My problem is that it just delete my previous input and make new inputs. Hoping for your great cooperation. Thanks.
<html>
<script type="text/javascript">
function disable_btn_limit(btn_name)
{
/* this function is used to disable and enable buttons and textbox*/
if(btn_name == "btn_limit")
{
document.getElementById("btn_limit").disabled = true;
document.getElementById("ctr_limit_txt").disabled = true;
document.getElementById("btn_edit_limit").disabled = false;
}
if(btn_name == "btn_edit_limit")
{
document.getElementById("btn_limit").disabled = false;
document.getElementById("ctr_limit_txt").disabled = false;
document.getElementById("btn_edit_limit").disabled = true;
}
}
function check_content(txtarea_content)
{
/*This function is used to check the content*/
// initialize an array
var txtArr = new Array();
//array assignment
//.split(delimiter) function of JS is used to separate
//values according to groups; delimiter can be ;,| and etc
txtArr = txtarea_content.split("");
var newcontent = "";
var momo = new Array();
var trimmedcontent = "";
var re = 0;
var etoits;
var etoits2;
//for..in is a looping statement for Arrays in JS. This is similar to foreach in C#
//Syntax: for(index in arr_containter) {}
for(ind_val in txtArr)
{
var bool_check = check_if_Number(txtArr[ind_val])
if(bool_check == true)
{
//DO NOTHING
}
else
{
//trim_content(newcontent);
newcontent += txtArr[ind_val];
momo[ind_val] = txtArr[ind_val];
}
}
var isapa = new Array();
var s;
re = trim_content(newcontent);
for(var x = 0; x < re - 1; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
}
function trim_content(ContentVal)
{
//This function is used to determine length of content
//parseInt(value) is used to change String values to Integer data types.
//Please note that all value coming from diplay are all in String data Type
var limit_char =parseInt(document.getElementById("ctr_limit_txt").value);
var eto;
if(ContentVal.length > (limit_char-1))
{
alert("Length is greater than the value specified above: " +limit_char);
eto = limit_char ;
etoits = document.getElementById("txtarea_content").value;
//document.getElementById("txtarea_content").value = "etoits";
return eto;
//for(var me = 0; me < limit_char; me++)
//{document.getElementById("txtarea_content").value = "";}
}
return 0;
}
function check_if_Number(ContentVal)
{
//This function is used to check if a value is a number or not
//isNaN, case sensitive, JS function used to determine if the values are
//numbers or not. TRUE = not a number, FALSE = number
if(isNaN(ContentVal))
{
return false;
}
else
{ alert("Input characters only!");
return true;
}
}
</script>
<table>
<tr>
<td>
<input type="text" name="ctr_limit_txt" id="ctr_limit_txt"/>
</td>
<td>
<input type="button" name="btn_limit" id="btn_limit" value="Set Limit" onClick="javascript:disable_btn_limit('btn_limit');"/>
</td>
<td>
<input type="button" name="btn_edit_limit" id="btn_edit_limit" value="Edit Limit" disabled="true" onClick="javascript:disable_btn_limit('btn_edit_limit');"/>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtarea_content" id="txtarea_content" onKeyPress="javascript:check_content(this.value);"></textarea>
<br>
*Please note that you cannot include <br>numbers inside the text area
</td>
</tr>
</html>
Try this. If the condition is satisfied return true, otherwise return false.
<html>
<head>
<script type="text/javascript">
function check_content(){
var text = document.getElementById("txtarea_content").value;
if(text.length >= 3){
alert('Length should not be greater than 3');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div>
<textarea name="txtarea_content" id="txtarea_content" onkeypress=" return check_content();"></textarea>
</div>
</body>
</html>
Instead of removing the extra character from the text area, you can prevent the character from being written in the first place
function check_content(event) { //PARAMETER is the event NOT the content
txtarea_content = document.getElementById("txtarea_content").value; //Get the content
[...]
re = trim_content(newcontent);
if (re > 0) {
event.preventDefault(); // in case the content exceeds the limit, prevent defaultaction ie write the extra character
}
/*for (var x = 0; x < re - 1; x++) {
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}*/
}
And in the HTML (parameter is the event):
<textarea ... onKeyPress="javascript:check_content(event);"></textarea>
Try replacing with this:
for(var x = 0; x < re - 6; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
Any reason why the maxlength attribute on a text input wouldn't work for so few characters? In your case, you would have:
<input type="text" maxlength="3" />
or if HTML5, you could still use a textarea:
<textarea maxlength="3"> ...
And then just have a label that indicates a three-character limit on any input.

Categories