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
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.
Related
I have a shopping cart that doesn't validate cards and I'm getting a lot of declined orders because people don't catch their typos. Trying to add Luhn validation to it.
I found this script which works fine by itself. It on-the-fly changes invalid to valid when a "good" credit card number is typed in.
<input id="cc" type="text" name="creditcard" size="20"><p id="status">invalid</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('#cc').on('input', function(){
if (checkLuhn($('#cc').val())) {
$('#status').html('valid');
} else {
$('#status').html('invalid');
}
});
function checkLuhn(value) {
// remove all non digit characters
var value = value.replace(/\D/g, '');
var sum = 0;
var shouldDouble = false;
// loop through values starting at the rightmost side
for (var i = value.length - 1; i >= 0; i--) {
var digit = parseInt(value.charAt(i));
if (shouldDouble) {
if ((digit *= 2) > 9) digit -= 9;
}
sum += digit;
shouldDouble = !shouldDouble;
}
return (sum % 10) == 0;
}
</script>
I'm trying to insert it into the HTML portion of the CGI file, below this relevant line and giving the INPUT the id="cc" tag, but the script won't run.
<INPUT TYPE="text" id="cc" NAME="Payment_Card_Number" MAXLENGTH="20" size="20" value="$form_data{'Payment_Card_Number'}">
So I'm trying to get the error message to go next to the field, but I have no idea what I'm doing, I'm pretty new at this, sorry to bother you guys.
Here's the whole code:
function computeBMI() {
var height = 0;
var weight = 0;
height = Number(document.getElementById("height").value);
weight = Number(document.getElementById("weight").value);
if (height == 0 | height > 220) {
document.getElementById('errorMsg').innerHTML = "Use Appropriate Height";
return 0;
}
if (weight == 0 | weight < 20) {
document.getElementById('errorMsg').innerHTML = "Use Appropriate Weight";
return 0;
}
var BMI = weight / (height / 100 * height / 100);
document.getElementById("output").innerText = Math.round(BMI * 100) / 100;
var output = Math.round(BMI * 100) / 100;
if (output < 18.5)
document.getElementById("comment").innerText = "Underweight";
else if (output >= 18.5 && output <= 25)
document.getElementById("comment").innerText = "Normal";
else if (output > 25)
document.getElementById("comment").innerText = "Overweight";
}
<html>
<head>
<title>BMI Calculator</title>
</head>
<body>
<div id="errorMsg"></div>
<h1>Body Mass Index Calculator</h1>
<p>Enter your height: <input type="text" id="height" /></p> <span id="errorMsg"><
<p>Enter your weight: <input type="text" id="weight"/></p>
<input type="submit" value="computeBMI" onclick="computeBMI();">
<h1>Your BMI is: <span id="output">?</span></h1>
<h2>This means you are: <span id="comment"> ?</span> </h2>
</body>
To do it your way you would need a separate error message area next to each input, and each one would need a unique ID - currently you have two elements whose ID is "errorMsg", one of which is in the wrong place in the layout. An ID must (by definition) uniquely identify an element, so clearly that isn't going to work. When you refer to "errorMsg" in your code, JavaScript will just pick the first one it finds and assume you meant that one. It has no way of telling them apart.
But anyway for the validation you're trying to do, you don't actually need to write your own code at all. If you put your fields inside a form, and handle the submit event of the form, you can then use HTML5 validation rules on the fields themselves to restrict the allowed input.
Here's a demo:
Note the addEventListener to handle the "submit" event of the form and run some Javascript.
Note also the <form> and </form> tags round the fields and button, and lastly the type="number", required, min and max attributes on the input fields themselves.
var form = document.getElementById("BMIForm");
form.addEventListener("submit", function(event) {
event.preventDefault(); //stop a postback
computeBMI();
});
function computeBMI() {
var height = 0;
var weight = 0;
height = Number(document.getElementById("height").value);
weight = Number(document.getElementById("weight").value);
var BMI = weight / (height / 100 * height / 100);
document.getElementById("output").innerText = Math.round(BMI * 100) / 100;
var output = Math.round(BMI * 100) / 100;
if (output < 18.5)
document.getElementById("comment").innerText = "Underweight";
else if (output >= 18.5 && output <= 25)
document.getElementById("comment").innerText = "Normal";
else if (output > 25)
document.getElementById("comment").innerText = "Overweight";
}
<html>
<head>
<title>BMI Calculator</title>
</head>
<body>
<h1>Body Mass Index Calculator</h1>
<form id="BMIForm">
<p>Enter your height: <input type="number" required min="0" max="220" id="height" /></p>
<p>Enter your weight: <input type="number" required min="0" max="20" id="weight"/></p>
<input type="submit" value="computeBMI">
</form>
<h1>Your BMI is: <span id="output">?</span></h1>
<h2>This means you are: <span id="comment"> ?</span> </h2>
</body>
You can learn more about HTML form validation here: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation
You tried to use an element's ID, but you can only select one element using ID. You have to use class, and then select which element in the satisfying list of elements contain the class you want.
Also, I updated your code a little bit so instead of validating if the answer fits in an anti-category, it checks if it does not fit in a specified category.
function computeBMI() {
document.getElementsByClassName('errorMsg')[0].innerHTML = ""
document.getElementsByClassName('errorMsg')[1].innerHTML = ""
var height = parseInt(document.getElementById("height").value);
var weight = parseInt(document.getElementById("weight").value);
var returnVal = false
if (!(height > 0 && height <= 220)) {
document.getElementsByClassName('errorMsg')[0].innerHTML = "Use Appropriate Height";
returnVal = returnVal || true
}
if (!(weight > 0 && weight < 20)) {
document.getElementsByClassName('errorMsg')[1].innerHTML = "Use Appropriate Weight";
returnVal = returnVal || true
}
if (returnVal) {
return 0
}
var BMI = weight / (height / 100 * height / 100);
document.getElementById("output").innerText = Math.round(BMI * 100) / 100;
var output = Math.round(BMI * 100) / 100;
if (output < 18.5)
document.getElementById("comment").innerText = "Underweight";
else if (output >= 18.5 && output <= 25)
document.getElementById("comment").innerText = "Normal";
else if (output > 25)
document.getElementById("comment").innerText = "Overweight";
}
<html>
<head>
<title>BMI Calculator</title>
</head>
<body>
<h1>Body Mass Index Calculator</h1>
Enter your height:
<input type="text" id="height" placeholder="height" />
<span class="errorMsg"></span><br> Enter your weight:
<input type="text" id="weight" placeholder="weight" />
<span class="errorMsg"></span><br>
<input type="submit" value="computeBMI" onclick="computeBMI();">
<h1>Your BMI is: <span id="output">?</span></h1>
<h2>This means you are: <span id="comment"> ?</span> </h2>
</body>
I have no JS or other language background. I have learned everything in the code for this particular problem so bear with me if things aren't clean and clever. I have done a lot of searching before resulting to asking here, so hopefully ALMOST everything is accounted for.
I have a conditional statement I just CANNOT get to run correctly. (entire code for context at the bottom)
if (pyramid < 1 || pyramid > 8) {
var dennis = document.getElementById("dennis");
var showdennis = "#ahahah{display: block}";
dennis.appendChild(document.createTextNode(showdennis));
document.getElementById("giza").innerHTML = "";
return;
}
I am most concerned with (pyramid < 1 || pyramid > 8) but if you can help me account for an input value of zero (due to complexities with 0 being false-y), bonus points.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<style id="dennis">
#ahahah {
display: none;
}
</style>
</head>
<body>
<h1>Text Box Input and Output</h1>
<form action="">
<fieldset>
<label>write how tall </label>
<input type="number" id="numberin" min="" max="" step="1" />
<input type="button" value="Make the Pyramid" onclick="makepyramid()" />
</fieldset>
</form>
<script type="text/javascript">
function makepyramid() {
var numberin = document.getElementById("numberin");
var pyramid = numberin.value;
var spaceincrement = numberin.value;
var octoincrement = numberin.value;
var spaces;
var octothorps;
var bringittogether = "";
//WHY YOU NO WORK?! I'd like to make 0 work as well but I am more concerned with the range first.
//first if statement is the ideal, second is bare minimum.
//if (pyramid === null || pyramid < 1 || pyramid > 8) {
//if (pyramid < 1 || pyramid > 8) {
//Put in this if statement to show what SHOULD happen
if (pyramid > 8) {
var dennis = document.getElementById("dennis");
var showdennis = "#ahahah{display: block}";
dennis.appendChild(document.createTextNode(showdennis));
document.getElementById("giza").innerHTML = "";
return;
} else {
document.getElementById("ahahah").innerHTML = "";
//decide how many lines to make
for (var a = 0; a < pyramid; a++) {
//number of spaces loop
for (var b = 1, spaces = ""; b < spaceincrement; b++) {
spaces += "_";
}
//number of octothorps in one line loop
for (var c = pyramid, octothorps = ""; c >= octoincrement; c--) {
octothorps += "#";
}
//print spaces, hashes, 2 spaces, start new line
bringittogether += spaces + octothorps + "__" + octothorps + "<br/>";
document.getElementById("giza").innerHTML = bringittogether;
//increment to change next line's number of spaces (one less) and octothorps (one more)
spaceincrement = [spaceincrement - 1];
octoincrement = [octoincrement - 1];
}
}
}
</script>
<hr />
<div id="giza"></div>
<div id="ahahah">
<p><img src="https://i.imgur.com/1A8Zgnh.gif" /> You must select a number between 1 and 8
</p>
</div>
</body>
</html>
I have a Rot13 JS function that I am attempting to link to a button. The expected output is meant to be that if I enter 'ABC' and press the Encrypt button, the encrypted text becomes 'NOP'.
The function doesn't currently link up to the buttons in HTML and when I press the encrypt button there is no response. I've included a script tag in the HTML.
EDIT: the encrypter is linked to the button, however it encrypts 'ABC' to 'ABC.
JavaScript:
function rot13() {
var input = document.getElementById("box1").value;
var output = [];
for (var i = 0; i < input.length; i++) {
var asciiNum = input[i].charCodeAt();
if (asciiNum >= 65 && asciiNum <= 77) {
output.push(String.fromCharCode(asciiNum + 13))
} else if (asciiNum >= 78 && asciiNum <= 90) {
output.push(String.fromCharCode(asciiNum - 13))
} else {
output.push(input[i])
}
}
document.getElementById("box2").value = output.join('');
}
<div class="form">
<input type="text" placeholder="plain text here..." name="plaintext" id="box1">
<br>
<button type="button" onclick="rot13()">Encrypt</button>
<button type="button" onclick="rot13()">Decrypt</button>
<br>
<input type="text" placeholder="encrypted message here..." name="encryptedtext" id="box2">
</div>
EDIT: corrected the JS.
There are few problems with code:
output.join('') = document.getElementById("box2") will throw error. You should set .value to output.join(''). The left hand side of = should be a variable. output.join('') returns are value and it cannot be assigned to anything.
output + input[i] will do nothing. You should use push() to add values to array.
function rot13() {
var input = document.getElementById("box1").value;
var output = [];
for (var i = 0; i < input.length; i++) {
var asciiNum = input[i].charCodeAt();
if (asciiNum >= 65 && asciiNum <= 77) {
output.push(String.fromCharCode(asciiNum + 13))
} else if (asciiNum >= 78 && asciiNum <= 90) {
output.push(String.fromCharCode(asciiNum - 13))
} else {
output.push(input[i])
}
}
document.getElementById("box2").value = output.join('');
}
<div class="form">
<input type="text" placeholder="plain text here..." name="plaintext" id="box1">
<br>
<button type="button" onclick="rot13()">Encrypt</button>
<button type="button" onclick="rot13()">Decrypt</button>
<br>
<input type="text" placeholder="encrypted message here..." name="encryptedtext" id="box2">
</div>
I feel like I'm progressing a little, I still have difficulties figuring out what to do when I'm stuck with Javascript. It's very hard but I need to get this coding done urgently.. so any help is greatly appreciated.
It's really simple, I want to make my own converter from Kelvin, Celsius and Fahrenheit. So I made these 3 variables, but I kind of realised they need their own formula, so do I need a different variable for the result? And if so where does it go? All these functions are so confusing.
This is my code.
<form>
Kelvin is
<input id="kelvin" size="7" maxlength="5" type="text" placeholder="vul in" />
<p></p>
Celsius is
<input id="celsius" size="7" maxlength="9" type="text" placeholder="vul in" />
<p></p>
Fahrenheit is
<input id="fahrenheit" size="7" maxlength="9" type="text" placeholder="vul in" />
<p></p>
<input id="calculate" type="button" value="Bereken!" />
</form>
<div id="calc">Dit is kelvin
<p></p>dit is celsius
dit is fahrenheit
and then the script
<table cellSpacing=0 cellPadding=0 width=250 border=0>
document.getElementById('calculate').addEventListener('click', function() {
var kel= document.getElementById("kelvin").value;
var cel = document.getElementById("celsius").value;
var far = document.getElementById("fahrenheit").value;
var div = document.getElementById('calc');
if (( kel < 0 || cel < -273 || far < -459 || isNaN(kel) || isNaN(bev)) {
div.innerHTML = "Not valid!";
return;
}
kel = parseInt(kelvin); cel = parseInt(celsius); far = parseInt (fahrenheit);
var far = (cel * (9/5) + 35;
var kel = cel + 273;
var cel = kel - 273;
var cel = (far -32)*(5/9);
if (far = kel ) {
var text = "hello? what to do here";
}
div.innerHTML = "Het is <b>" + kelvin+ "</b> Kelvin <p></p> en het is <b>" + celcius + "</b>" en het is <b>" + fahrenheit + "</b>";
}, false);
First of all
if (far = kel ) {
var text = "hello? what to do here";
}
should be
if (far === kel ) {
var text = "hello? what to do here";
}
= is used to define variables eg. var a = 10;
=== is used to compare two values
Also, you put
<table cellSpacing=0 cellPadding=0 width=250 border=0>
in the middle of the script. Which I hope was a mistake.
Which is best written
<table cellspacing='0' cellpadding='0' width='250' border='0'>
To be compliant with newer stricter XHTML standards.
Also, this:
if (( kel < 0 || cel < -273 || far < -459 || isNaN(kel) || isNaN(bev)) {
div.innerHTML = "Not valid!";
return;
}
needs to be replaced by this:
if ( kel < 0 || cel < -273 || far < -459 || isNaN(kel) || isNaN(cel) || isNaN(far)) {
document.getElementById('calc').innerHTML = "Not valid!";
}
And this:
kel = parseInt(kelvin); cel = parseInt(celsius); far = parseInt (fahrenheit);
Should read:
kel = parseInt(document.getElementById("kelvin").value); cel = parseInt(document.getElementById("celcius").value); far = parseInt (document.getElementById("fahrenheit").value);
Claies has a good point too.
if(kel != ''){
//Kelvin is the chosen one
}else if(far != ''){
//Fahrenheit is the chosen one
}else if(cel != ''){
//Celcius is the chosen one
}else{
//User hasn't written anything
alert('You need to write something to convert!');
}