I am making a website in HTML5 and Javascript which takes in some plaintext through textarea, applies a caesar cipher of 3, and sends the output to another textarea.
However, it does not produce any output.
Here is my code:
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript">
var x = document.getElementById("myTextArea").value;
function c_ciph(){
for (var i = 0, len = x.length; i < len; i++) {
if (x[i] == x[i].toUpperCase()){
var a = x[i].charCodeAt(0);
var e = ((a - 65 + 3) % 26) + 97;
var c = String.fromCharCode(e);
}
else if (x[i] == x[i].toLowerCase()){
var a = x[i].charCodeAt(0);
var e = ((a - 97 + 3) % 26) + 97;
var c = String.fromCharCode(e);
}
}
document.getElementById('result').value = x;
}
</script>
<div>
<h1>Cipher and Leetspeak Converter</h1>
<p>Welcome to the cipher and leetspeak converter.</p>
</div>
<div>
<textarea id = "myTextArea" rows = "6" cols = "80">
</textarea>
<p>Convert to:</p>
</div>
<div>
<form>
<input type="radio" name="codingStyle" value="caesar_cipher" onclick="c_ciph();"> Caesar Cipher <br>
<input type="radio" name="codingStyle" value="vigenere_cipher"> Vigenere Cipher<br>
<input type="radio" name="codingStyle" value="leetspeak"> Leetspeak
</form>
</div>
<div>
<button type="button">Convert</button>
</div>
<div>
<textarea id = "result" rows = "6" cols = "80">
</textarea>
</div>
</body>
</html>
This is the site:
enter image description here
However, nothing shows up in the second text box when "Caesar Cipher"
is clicked.
I am new to Javascript and HTML, so please point out as many errors as you can.
EDIT 1: The output does appear in the 2nd text area now. However, I am having trouble changing the value of x to the ciphertext. It prints out the same value. See image here:
Instead of geek in the second textarea, there should be "iggm".
Please help.
You need to move the
var x = document.getElementById("myTextArea").value;
inside the function, So that each time function is called x is assigned new value.
function c_ciph(){
var x = document.getElementById("myTextArea").value;
for (var i = 0, len = x.length; i < len; i++) {
if (x[i] == x[i].toUpperCase()){
var a = x[i].charCodeAt(0);
var e = ((a - 65 + 3) % 26) + 97;
var c = String.fromCharCode(e);
}
else if (x[i] == x[i].toLowerCase()){
var a = x[i].charCodeAt(0);
var e = ((a - 97 + 3) % 26) + 97;
var c = String.fromCharCode(e);
}
}
document.getElementById('result').value = x;
}
Working example here
https://jsfiddle.net/vqsnmamy/2/
Related
How do I loop the output of 5 different inputs? I want to get the output looped so that 5 sets come out.
This is what i have tried:
I'm trying to loop this section along with my other 4 sections of user inputs.
<input id="myInput" type="text">
<button onclick="myFunction()">See your trip</button>
<p id="output1"></p>
<script>
function myFunction() {
A = 0;
B = 450;
C = 590;
D = 710;
E = 1030;
F = 1280;
G = 1360;
var startDistance;
var inputLine = document.getElementById("myInput").value;
for(i = 0; i < 5; i++) {
switch(inputLine[0]) {
case "A":
startDistance = A;
break;
case "B":
startDistance = B;
break;
case "C":
startDistance = C;
break;
Well, for starters... it appears that your code isn't formatted correctly, provided that you just didn't show all of it, which looks to be the case.
There is also this weird snippet inputLine[0]... is there an input that is holding an array as a value?
function myFunction()
{
A = 0;
B = 450;
C = 590;
D = 710;
E = 1030;
F = 1280;
G = 1360;
var startDistance;
var inputLine = document.getElementById("myInput").value;
for(i = 0; i < 5; i++)
{
switch(inputLine[0])
{
case "A":
startDistance = A;
break;
case "B":
startDistance = B;
break;
case "C":
startDistance = C;
break;
}
}
}
Anyway with all that being said... this code can be written way more dynamically with the idea being to give all inputs the same class name, selecting those inputs using javascript's document.getElementsByClassName() selector, then looping through the values of those. For instance:
function newDistanceInput()
{
var container = document.getElementById("input-container");
var newInput = "<span><input type='number' class='DistanceInput' oninput='if (this.value < 0) {this.value = 0;} calculateDistance();' value='0' /><span onclick='this.parentNode.remove(); calculateDistance();'>remove</span><br></span>";
container.innerHTML += newInput;
calculateDistance();
}
function calculateDistance()
{
distInputs = document.getElementsByClassName('DistanceInput');
totalLength = 0;
for (var i = 0; i < distInputs.length; i++)
{
totalLength += parseInt(distInputs[i].value);
}
document.getElementById('total-length').innerText = totalLength;
}
<html>
<body>
<div>
<button onclick="newDistanceInput();">
Add another distance input
</button>
<br>
<div id="input-container">
</div>
<div id="total-length">
</div>
</div>
</body>
</html>
---EDIT---
If you are referring to how to edit this post, you can go back to the top of the page, right after your question, you will see:
and the edit button is below it.
From there, in the textbox you type in, you can set up the same runable example by:
clicking the circled button.
I have to create a html page which satisfy below requirement-
1. print 1 to 5 with another array
2. take number input from textbox then print on page whether it is Even or Odd.
I have create a page but it is not working as desired.
<HTML>
<HEAD>
</HEAD>
<BODY>
<p id="demo"></p>
<input type="number" id="myNumber">
<button onclick="oddOrEven()">Try it</button>
<input type="text" name="result" id="result" readonly="true"/>
<SCRIPT>
var numbers = [1,2,3,4,5];
var myObjects = ["One","Two","Three","Four","Five"];
var text = "";
var myObjectsList =""
var i;
for (i = 0; i < numbers.length; i++) {
text += numbers[i] + " : " + myObjects[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
function oddOrEven() {
var value = document.getElementById("myNumber").value;
var res = if((value % 2) == 0) {"Even"} else {"Odd"}*/
//if(value % 2 == 0) document.write("Even")
//document.write(value);
//document.getElementById("demo").innerHTML = res;
readonly.value=res;
}
//document.write("Hello World!");
</SCRIPT>
</BODY>
</HTML>
Could someone please help me with the code.
please see the updated solution
var numbers = [1,2,3,4,5];
var myObjects = ["One","Two","Three","Four","Five"];
var text = "";
var myObjectsList =""
var i;
for (i = 0; i < numbers.length; i++) {
text += numbers[i] + " : " + myObjects[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
function oddOrEven() {
var value = document.getElementById("myNumber").value;
var res = value % 2 == 0 ? "Even" : "Odd";
document.getElementById("result").value=res;
}
//document.write("Hello World!");
<p id="demo"></p>
<input type="number" id="myNumber">
<button onclick="oddOrEven()">Try it</button>
<input type="text" name="result" id="result" readonly/>
Updated code
var numbers = [1,2,3,4,5];
var myObjects = ["One","Two","Three","Four","Five"];
var text = "";
var myObjectsList =""
var i;
for (i = 0; i < numbers.length; i++) {
text += numbers[i] + " : " + myObjects[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
function oddOrEven() {
var value = document.getElementById("myNumber").value;
var res = value % 2 == 0 ? "Even" : "Odd";
document.getElementById("result").innerHTML=res;
}
<p id="demo"></p>
<input type="number" id="myNumber">
<button onclick="oddOrEven()">Try it</button>
<p id="result"></p>
Update2
Replace
<p id="result"></p>
with
<span id="result"></span>
There is a problem with the way you are assigning res, it should be as follows:
var res = value % 2 == 0 ? "Even" : "Odd";
Alternatively you can use an if statement if you want like so:
var res = "Odd";
if(value % 2 == 0) {
res = "Even";
}
In addition, there is also an issue with this line:
readonly.value=res;
In this case, readonly does not exist. You probably mean to do this:
document.getElementById("result").value = res;
I am attempting to create an online solver for the maximum subarray problem.
https://en.wikipedia.org/wiki/Maximum_subarray_problem
I planned on taking user-input numbers from a textbox and converting them into an int array in JS, however my JS does not seem to be running at all.
Here is my HTML
<!DOCTYPE html>
<html>
<head>
<title> findMaxSum </title>
<script src="findMaxSum.js" type="text/javascript"></script>
</head>
<body>
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p> Enter numbers with spaces, i.e. "1 2 3 4 5": </p>
<input type="text" id="array"> <br>
<button id="sum">findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is: </p>
</body>
</html>
and my JS. note: the map(function(item)) part of the code is intended to break apart the string from the form into an int array.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Currently, when I type in numbers into the textbox and submit, the numbers disappear and nothing happens. Any help is greatly appreciated.
Your array variable is object. You have to split the value of <input type="text" id="array"> not the object element.
var array = document.getElementById("array");
array = array.value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Or simpler:
var array = document.getElementById("array").value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Change your code -
function findMaxSum() {
var array = document.getElementById("array").value.split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Problem is you are using button inside form, which is by default of type submit type, that is the reason why the page goes blank, it gets submitted. So either you don't use form tag or make the button as button type.
<button id="sum" type='button'>findMaxSum!</button> <!-- type attribute added -->
Below is the sample updated code, hope it helps you.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").value.split(/\s/);
var max = Math.max.apply(Math, array);
document.getElementById("answer").innerHTML = "The answer is: " + max;
}
window.onload = function() {
document.getElementById("sum").onclick = findMaxSum;
};
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p>Enter numbers with spaces, i.e. "1 2 3 4 5":</p>
<input type="text" id="array">
<br>
<button id="sum" type='button'>findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is:</p>
To achieve the solution of the problem, you need to make following changes.
Update the event binding place
window.onload = function() {
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
};
function findMaxSum() {
// remove the update binding code from here
// logic should come here
}
Resolve a JS error
document.getElementById("array").value.split(" ")
Update the html to avoid page refresh (add type)
<button id="sum" type='button'>findMaxSum!</button>
Update the logic to address the problem
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
var counter = i+1;
while (counter < array.length) {
var loopSum = array[i];
for (var j = (i+1); j <= counter; j++) {
loopSum += array[j];
if(loopSum > currentMax) {
currentMax = loopSum;
}
}
counter++;
}
}
Here is a plunker - http://plnkr.co/edit/AoPANUgKY5gbYYWUT1KJ?p=preview
I have a bit of an issue at the moment that I am hoping one of you can help me with. I have tried several things, and I just can't get it. I am trying to print a triangle of asterisks using JavaScript. The program is to ask the user for the amount of rows, and then the direction. I haven't even started with the direction yet because I can't get the rows to work. Odd thing is that I can get it to print out the triangle hard-coding the function call.
This is the JS file:
function myTriangle(){
var result = "";
var totalRows = document.getElementById('rows').value;
var direction = document.getElementById('UpOrDown').value;
for (var i = 1; i <= totalRows; i++){
document.writeln("count");
for (var j = 1; j <= 1; j++)
{
result += "*";
}
result += "<br/>";
}
return result;
}
var answer = myTriangle();
document.getElementById('myDiv').innerHTML = answer;
This is the HTML file:
<!DOCTYPE html>
<head>
<title>Lab 2</title>
<script src="scripts.js", "div.js"></script>
</head>
<body>
<form name="myForm">
<fieldset>
<legend>Input Fields</legend>
rows: <input type="text" id="rows" /><br>
direction: <input type="text" id="UpOrDown" /><br>
press: <input type="button" value="GO!" id="myButton"
onclick="myTriangle();"/>
</fieldset>
</form>
<div id="myDiv">
</div>
</body>
The output will be something like this:
*
**
***
****
*****
Generally there are four types of triangle -
1.)* 2.) *** 3.) * 4.) ***
** ** ** **
*** * *** *
Code for 1 -
var ast = [],
i, j = 4;
for (i = 0; i < j; i++) {
ast[i] = new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 2 -
var ast = [],
i, j = 4;
for (i = j-1; i >=0; i--) {
ast[i] = new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 3 -
var ast = [],
i, j = 4;
for (i = 0; i < j; i++) {
ast[i] = new Array(j - i).join(' ') + new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 4 -
var ast = [],
i, j = 4;
for (i = j-1; i >=0; i--) {
ast[i] = new Array(j - i).join(' ') + new Array(i + 2).join("*");
console.log(ast[i]);
}
To print asterisk in document rather than console -
document.getElementById('anyElement').innerHTML+=ast[i] + '<br />';
document.writeln will completely wipe the page unless it's called while the page is loading.
Therefore it will destroy myDiv, causing the getElementById to fail.
Furthermore, I'm not sure what you're trying to achieve with that <script> tag, but it looks like you need two of them.
EDIT: Oh, and this: for (var j = 1; j <= 1; j++) will only ever iterate once.
EDIT 2: Here's my implementation of a solution.
This isn't a valid script tag.
<script src="scripts.js", "div.js"></script>
You need to break it up into two tags:
<script src="scripts.js"></script>
<script src="div.js"></script>
This is my solution, it uses es2015 .replace() but there is a nice
polyfill for es5 as well here:
var output = document.getElementById('output');
function triangle (size) {
for (var i = 1; i <= size; i++) {
output.innerHTML += '*'.repeat(i) + '<br>';
}
}
triangle(2);
This is a solution in ES3/5
var output = document.getElementById('output');
function triangle(size) {
var allLines = '';
for (var i = 1; i <= size; i++) {
var oneLine = createLine(i);
allLines += oneLine;
}
return allLines;
}
function createLine(length) {
var aLine = '';
for (var j = 1; j <= length; j++) {
aLine += '*';
}
return aLine + "<br/>";
}
output.innerHTML += triangle(3);
<div id='output'></div>
i am trying to create a page that has a two textboxes where the user can choose how many rows and columns they want. A grid is of textboxes is then created for their requirements, with an added column and row of disabled text boxes to calculate the sum of each row and column. The function sums all the rows but i am really struggling to sum the rows. Here is the code so far.
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8">
<title></title>
<script>
function grid() {
var row = document.getElementById("rows");
var column = document.getElementById("columns");
row.value = parseInt(row.value);
column.value = parseInt(column.value);
for (var x = 0; x <= parseInt(row.value); x++) {
for (var y = 0; y <= parseInt(column.value); y++){
var br = document.createElement("br");
var box = document.createElement("input")
box.setAttribute("type", "text");
box.setAttribute("size", "5");
box.setAttribute("id", "tb" + x + y);
box.setAttribute("name", "add" + x);
box.setAttribute("value", "0");
box.style.marginRight = "3px";
box.style.marginBottom = "3px";
var output = document.createElement("input");
output.setAttribute("id", "output" + parseInt(x) + parseInt(y))
output.setAttribute("name", "result" + x);
output.setAttribute("disabled", "true");
output.setAttribute("size", "5");
output.style.marginRight = "3px";
if (x < parseInt(row.value)){
if (y < parseInt(column.value)){
document.getElementById("boxs").parentNode.appendChild(box);
}else{
document.getElementById("boxs").parentNode.appendChild(output);
document.getElementById("boxs").parentNode.appendChild(br);
}
}else{
document.getElementById("boxs").parentNode.appendChild(output);
}
}
}
//remove last box
tbid = "output" + (row.value) + (column.value);
nobox = document.getElementById(tbid);
nobox.parentNode.removeChild(nobox);
}
</script>
<script>
function calculate(){
var row = document.getElementById("rows");
var column = document.getElementById("columns");
row.value = parseInt(row.value);
column.value = parseInt(column.value);
var perform = document.getElementById("perform");
for (var x = 0; x < parseInt(row.value); x++) {
var arr = document.getElementsByName("add" + x);
var rowTotal = 0;
var colTotal = 0;
for(var y = 0 ; y < parseInt(column.value); y++){
if(parseInt(arr[y].value))
rowTotal += parseInt(arr[y].value);
}
if(perform.value == "sum"){
document.getElementById("output" + x + y).value = rowTotal;
}else if(perform.value == "mean"){
document.getElementById("output" + x + y).value = rowTotal / parseInt(row.value);
}
}
}
</script>
</head>
<body>
<div>
<div id="boxs">
</div>
<div id="matrix">
Rows<input type="text" id="rows">
Columns<input type="text" id="columns">
<button id="button" onclick="grid()">Create Grid</button><br><br>
<select id="perform">
<option value="sum">sum</option>
<option value="mean">Mean</option>
<option value="mode">Mode</option>
<option value="median">Median</option>
</select><br>
<button id="calculate" onclick="calculate()">Calculate</button><br><br>
</div>
</div>
</body>
I realize its probably quite messy but i am very new to this. Any help or guidance would be very much appreciated. Thanks in advance.
Give your inputs a row and column class. Then you can use a selector to get the collection of inputs easily. After that it's just a matter of iterating through the collections and calculate the sum however you like.
<input type="text" class="row1 col1" />
<input type="text" class="row1 col2" />
<input type="text" class="row2 col1" />
<input type="text" class="row2 col2" />
var row1 = document.querySelectorAll(".row1");
var row2 = document.querySelectorAll(".row2");
var col1 = document.querySelectorAll(".col1");
var col2 = document.querySelectorAll(".col2");
var sum = 0;
for (var i = 0; i < row1.length; i++) {
sum += parseInt(row1[i].value));
}
for calculating row total.
just changed few things in column total to get row total
for (var x = 0; x < parseInt(column.value); x++) {
var colTotal = 0;
for(var y = 0 ; y < parseInt(row.value); y++){
var arr = document.getElementsByName("add" + y);
if(parseInt(arr[x].value))
colTotal += parseInt(arr[x].value);
}
if(perform.value == "sum"){
document.getElementById("output" + y + x).value = colTotal;
}else if(perform.value == "mean"){
document.getElementById("output" + y + x).value = colTotal / parseInt(row.value);
}
}
Simply add a specific class to the input elements when you create them. After that you can easily select every input in a single query.
Also: use jquery :)
The entire JS code for calculation will be something like this:
var sum = 0;
$('.classname').each(function(){
sum += $(this).val();
});