This question already has answers here:
What are alternatives to document.write?
(11 answers)
Closed 5 years ago.
(I am new to programming)
The program: I have made a relatively simple JavaScript program, that generates a password when you click on a button.
The problem: Displaying the password with document.write, the whole page is overwritten, meaning that the button is removed and you have no opportunity to generate a new password. Therefore, I would like the password to go inside the paragraph with Id "pw".
Note that document.write is disabled in JSFiddle, so the result is set to display in console.
JSFiddle: https://jsfiddle.net/3qh01ctp/1/
Thank you very much in advance, any help/advice appreciated!
var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
function generate () {
for (i = 0; i < 10; i++) {
randomLetter = arr[Math.floor(arr.length * Math.random())];
console.log(randomLetter);
}
}
<!DOCTYPE html>
<html>
<head>
<button onclick="generate();">Generate password</button>
</head>
<body>
<p id="pw">
<!-- password should go here -->
</p>
</body>
</html>
You shouldn't use document.write(). Nowadays, you usually select an element, and then push the content into it. You can select an element by e.g. one of the following methods:
document.getElementById(): selects an element by its ID, it is very fast
document.querySelector(): selects an element by its CSS selector (not that fast, but good enough)
So here is an example:
var pw = 'password';
document.getElementById('pw').textContent = pw;
Or with the querySelector:
var pw = 'password';
document.querySelector('#pw').textContent = pw;
I've used .textContent on the node, because it prevents accidental HTML injection. If you explicitly want to allow HTML, you can also use .innerHTML.
And finally, here the complete example (including a button to execute the function):
var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
function generate () {
var password = "";
for (i = 0; i < 10; i++) {
var randomLetter = arr[Math.floor(arr.length * Math.random())];
password += randomLetter;
}
document.getElementById("pw").textContent = password;
}
document.querySelector('#button-clicker').addEventListener('click', function (event) {
event.preventDefault();
generate();
});
<p id="pw"></p>
<button id="button-clicker">click</button>
var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
function generate () {
var randomLetter="";
for (i = 0; i < 10; i++) {
randomLetter += arr[Math.floor(arr.length * Math.random())];
//console.log(randomLetter);
}
document.getElementById("pw").innerText =randomLetter ;
}
<!DOCTYPE html>
<html>
<head>
<button onclick="generate();">Generate password</button>
</head>
<body>
<p id="pw">
<!-- password should go here -->
</p>
</body>
</html>
I updated your code please check. using id of you p tag you can place text on that. In you loop keep appending to randomLetter after looping just give it to innerHTML of your p tag document.getElementById("pw").innerHTML = randomLetter;
var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
var randomLetter ='';
function generate () {
for (i = 0; i < 10; i++) {
randomLetter += arr[Math.floor(arr.length * Math.random())];
}
document.getElementById("pw").innerHTML = randomLetter;
randomLetter ='';
}
<!DOCTYPE html>
<html>
<head>
<button onclick="generate();">Generate password</button>
</head>
<body>
<p id="pw">
<!-- password should go here -->
</p>
</body>
</html>
what you have to do is , Populate the content i.e Random Generated Password in Seprate HTML Body content , it can be Paragraph or Div, Use the java script code as :
document.getElementById('YOUR FIELD ID').innerHTML = "YOUR TEXT";
Do this in your script tag.
var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
function generate () {
var randomLetter = "";
for (i = 0; i < 10; i++) {
randomLetter += arr[Math.floor(arr.length * Math.random())];
}
var paraElem = document.getElementById("pw");
var t = document.createTextNode(randomLetter);
paraElem.appendChild(t)
}
Related
I am trying to create a Caesar cipher that permanently shifts by 3 and deals with the end of the array using modularisation. Currently, when I run the function it outputs the letters as undefined and I'm not entirely sure why.
function caesarCipher() {
let letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
let shift = 3;
let outputString = "";
let userString = document.getElementById("input").value;
for (count = 0; count < userString.length - 1; count++) {
let character = userString[count];
let letterIndex = letters[character];
let newIndex = (letterIndex + shift) % 26;
let newCharacter = letters[newIndex];
outputString = outputString + newCharacter;
}
document.getElementById("output").value = outputString;
}
<div id="alignment">
<label for="input">String Input</label>
<input type="text" id="input" placeholder="Unciphered">
<input type="submit" id="button" value="CIPHER STRING" onclick="caesarCipher()">
<label for="input">String Output</label>
<input type="text" id="output" placeholder="Ciphered">
</div>
You are not looking for the index. If you entered "A" You are looking for letters["A"]. The array code is not going to find the index with A in it. You need to use indexOf to find it. You are also not looping through the whole array because of the -1 in the length check.
function caesarCipher() {
let letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
let shift = 3;
let outputString = "";
let userString = document.getElementById("input").value;
for (count = 0; count < userString.length; count++) {
const character = userString[count];
const letterIndex = letters.indexOf(character);
const newIndex = (letterIndex + shift) % 26;
const newCharacter = letters[newIndex];
outputString = outputString + newCharacter;
}
document.getElementById("output").value = outputString;
}
<div id="alignment">
<label for="input">String Input</label>
<input type="text" id="input" placeholder="Unciphered">
<input type="submit" id="button" value="CIPHER STRING" onclick="caesarCipher()">
<label for="input">String Output</label>
<input type="text" id="output" placeholder="Ciphered">
</div>
Maybe this simple script will help. Just insert it in your file.
function rot3(str) {
let regex = /[\W]/g
return str.split('').map(i => regex.test(i)
? i
: String.fromCharCode(i.charCodeAt() + 3 > 90
? (i.charCodeAt() + 3 - 26)
: i.charCodeAt() + 3)
).join("")
}
console.log(rot3("COBB"))
I am trying to complete a codewars challenge as my practice coding since I will have a beginner tech test to enter a coding training program. In case you would like to know what the challenge is: https://www.codewars.com/kata/530e15517bc88ac656000716/train/javascript
I have written code which does what is expected. I will quote Codewars.com below:
ROT13 is a simple letter substitution cipher that replaces a letter
with the letter 13 letters after it in the alphabet. ROT13 is an
example of the Caesar cipher.
Create a function that takes a string and returns the string ciphered
with Rot13. If there are numbers or special characters included in the
string, they should be returned as they are. Only letters from the
latin/english alphabet should be shifted, like in the original Rot13
"implementation".
My code grabs the test string "grfg" and converts it to the word "test" which would be the equivalent to 13 letters ahead in the alphabet, however, if I pass the string as "Grfg" with the capital "G"it returns "gest" meaning that it will not replace capital letters.
If I pass "test" in lower case it will return "grfg", so it works backwards too, however, if I pass "Test" it will return "trfg" not replacing the capital again but returning the same letter.
Please find the code I wrote below:
function rot13(message){
let abc = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q",
"r", "s", "t", "u", "v", "w", "x", "y", "z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
let msg = message.split("");
for (let i = 0; i < abc.length; i++){
for (let j = 0; j < abc.length; j++) {
if (msg[j] === abc[i]) {
ind = parseInt(abc.indexOf(i), 0) + 13;
msg[j] = abc.slice(i + 13, i + 14);
};
};
};
return msg.join("").toLowerCase();
};
rot13("test");
What is my mistake or what I should know to make sure that my code will convert the strings regardless of capitals or lowercase?
Have you tried making the message all lower-case first, before splitting it?
let msg = message.toLowerCase().split("");
I was attempting to solve a problem on codewars but could not use the .join() method on my alphabet array because it was undefined with the following code:
function alphabetPosition(text) {
const alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
let numString = "";
let countArray = [];
for (x = 0; x < text.length; x++) {
for (y = 0; y < alphabet.length; y++) {
if (text[x].toLowerCase() === alphabet[y]) {
countArray += ++y;
}
}
}
return numString = countArray.join(" ");
}
console.log(alphabetPosition("The sunset sets at twelve o' clock."));
I was then able to solve the problem using the code below:
function alphabetPosition(text) {
const alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
let numString = "";
let countArray = [];
for (x = 0; x < text.length; x++) {
for (y = 0; y < alphabet.length; y++) {
if (text[x].toLowerCase() === alphabet[y]) {
countArray.push(++y);
}
}
}
return numString = countArray.join(" ");
}
console.log(alphabetPosition("The sunset sets at twelve o' clock."));
I am thinking that the .join() method did not work because I was not assigning an index in the countArray, whereas push appends to the array which would assign an index automatically?
You can't use countArray += ++y because arrays don't work that way in JavaScript like they do in some other languages. That's equivalent to countArray = countArray + ++y; which on the first iteration converts the array and the number to strings and concatenates them, assigning the result (a string) to countArray. So after that first iteration, countArray isn't an array anymore, and has no join method. Subsequent iterations are using + on a string and a number, and so convert the number to a string and append it to the string. You can see that in action if you log countArray at the outset and then on each iteration:
function alphabetPosition(text) {
const alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
let numString = "";
let countArray = [];
console.log(`initial (${typeof countArray}): `, countArray);
for (x = 0; x < text.length; x++) {
for (y = 0; y < alphabet.length; y++) {
if (text[x].toLowerCase() === alphabet[y]) {
countArray += ++y;
console.log(`x = ${x} (${typeof countArray}): `, countArray);
}
}
}
return numString = countArray.join(" ");
}
console.log(alphabetPosition("The sunset sets at twelve o' clock."));
.as-console-wrapper {
max-height: 100% !important;
}
The correct ways to add entries to the end of an array are:
countArray.push(++y);
or
countArray[countArray.length] = ++y;
I am working on creating a program to encrypt a message. One of the functions I was planning on running the code through is a circle cipher. It hasn't been working and I'm unsure as to why. At certain times the program will return the correct letters and at others it won't change anything and returns the same character that was input. Any suggestions are appreciated.
function circle(message, rotate) {
var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
for(i = 0; i < message.length; i++) {
for (i = 0; i < alphabet.length; i++) {
if (message[i] == alphabet[i]) {
message[i] = alphabet[i + rotate];
break;
}
}
}
return message;
}
I spot at least three bugs in your code:
You use the variable i twice. You should use another variable name for the inner loop.
You have to use remainder (modulus) operator to get the value i + rotate modulo 26.
Strings are immutable. So you can't change individual characters of a string.
For those familiar with this quiz, I'm trying to take a string argument and convert each letter to the letter that follows in the alphabet. EG, the argument "abc" should become "bcd".
The first portion of my code works. It takes the first letter of the argument and converts it. Now I'm trying to do this for each letter of the argument and then concatenate the results into one string as the output. This part isn't working. I'm getting the error, "SyntaxError: Unexpected token ;"
function LetterChanges(str) {
var string = str.toLowerCase()
var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
var n = 0;
var output = "";
var currentLetter = string[n];
var currentAlphaPos = alphabet.indexOf(currentLetter);
var nextAlphaPos = currentAlphaPos + 1;
var nextAlpha = alphabet[nextAlphaPos];
//the code above this works. The code below results in an error
while (i = 1;i < string.length; i++){
output += nextAlpha;
n += 1;
};
return output;
}
I'm a beginner, so thanks in advance.
You have confused the while and for loops.
You are trying to do for (iterator; condition; step); the while syntax is simply while (condition).