Generate Header for txt file - javascript

I am generating a default header for a given file and I want the sender ID to have 4 characters and the sender Name to have 45 characters. if they are less than 4 and 45 respectfully, I need to enter spaces to have the 4 or 45 characters. How can I do this?
In the figure below as you can see there are not filled in the necessary spaces for when I do blank file. And even if I write something on the sender ID or the sender Name nothing is added.
What am I doing wrong?
function download(fileName, text) {
let element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("generate").addEventListener("click", function(){
// Generate .txt file header
//force 4 chars
let id = document.getElementById("senderID");
if (id.textContent.length < 4) {
id.textContent += ' ';
}
//force 45 chars
let name = document.getElementById("senderName");
if (name.textContent.length < 45) {
name.textContent += ' ';
}
let header = "HDRPB" + id.textContent + name + "01.10";
let body = document.getElementById("fileContents").textContent;
let text = header;
let fileName = document.getElementById("fileName").value + ".txt";
download(fileName, text);
}, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="css/site.css">
<title>Generator</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-2 p-0 mt-2">
<label for="senderID" class="font-weight-bold">Sender ID:</label>
<input id="senderID" type="text" maxlength="4" size="4"/>
</div>
<div class="col-6 p-0 mt-2">
<label for="senderName" class="font-weight-bold">Sender Name:</label>
<input id="senderName" type="text" maxlength="45" size="45"/>
</div>
</div>
<div class="row mt-5">
<div class="col-10">
<label for="fileName" class="font-weight-bold">File Name:</label>
<input id="fileName" type="text"/>
</div>
<div class="col-2">
<button id="generate" type="button" class="btn btn-light font-weight-bold mx-auto">Generate File</button>
</div>
</div>
<div id="fileContents" class=""></div>
</div>
<script src="js/app.js"></script>
</body>
</html>

Consider the following code:
function genId(seed) {
var result = new Array(4);
for (var i = 0; i < 4; i++) {
result[i] = seed[i] || " ";
}
return result.join("");
}
function genName(seed) {
var result = new Array(45);
for (var c = 0; c < 45; c++) {
result[c] = seed[c] || " ";
}
return result.join("");
}
document.getElementById("genHead").addEventListener("click", function() {
var i = document.getElementById("hid").value;
var n = document.getElementById("hname").value;
var header = genId(i) + genName(n);
document.getElementById("results").innerHTML = header;
});
#results {
font-family: monospace;
border: 1px solid #ccc;
display: inline-block;
}
<p>ID: <input type="text" id="hid" /></p>
<p>Name: <input type="" id="hname" /></p>
<button id="genHead">Generate Header</button>
<div id="results"></div>
In this example, I am creating an Array of the specific number of characters. String is considered an Array of Characters anyway. I am using $nbsp; to represent spaces in HTML but you can use ' ' or " ".
There will always be a result due to result[c] = seed[c] || " "; If seed has a character in that position, it will be entered into result at the same position. Otherwise it will enter the No Break Space or the character you want.
You can also do this:
function formatText(t, n, c) {
if(t == undefined){
return "";
}
if(n == undefined){
n = 45;
}
if(c == undefined){
c = " ";
}
var r = new Array(n);
for (var i = 0; i < n; i++) {
r[i] = t[i] || c;
}
return r.join("");
}
Then use like so:
var i = formatText("12", 4, " ");
var n = formatText("test", 45, " ");
Hope this helps.

Related

Making Caser Cipher Case sensitive in JavaScript?

<body>
<div class="container">
<div class="row">
<h1 class="mx-auto">Secured Data Cypher</h1>
</div>
<div class="row">
<h5 class="mx-auto desc"><br><br>Enter Your Desired Message which you want Encrypted <br><br> For example: ****_***123 </h5>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<h4>Plain Text</h4>
<textarea class="form-control" id="plain-text" rows="7"></textarea>
</div>
<div class="input-group mb-3">
<input type="number" min="0" max="25" class="form-control" id="my-key" placeholder="Key (Digits Only)">
<div class="input-group-append">
<button class="btn btn-outline-success" type="button" onclick="encrypt()">Encrypt</button>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<h4>Cipher Text</h4>
<textarea readonly class="form-control" id="cipher-text" rows="7"></textarea>
</div>
<button type="button" class="btn btn-outline-danger" onclick="decrypt()">Decrypt</button>
</div>
<div class="col-sm-4">
<div class="form-group">
<h4>Original Text</h4>
<textarea readonly class="form-control" id="original-text" rows="7"></textarea>
</div>
</div>
</div>
</div>
</body>
<!- JS for Cypher Starts here ->
<script>
function encrypt() {
// Empty Original Text
document.getElementById("original-text").value = "";
var k = document.getElementById("my-key").value;
var p = document.getElementById("plain-text").value;
if (!(k >= 0 && k < 26)) {
alert("Key should be between 0 and 25");
return;
}
if (p.length === 0) {
alert("Plain Text is empty");
}
p = p.toLowerCase();
var cipher = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < p.length; i++) {
var current = p.charAt(i);
if (!isLetter(current)) {
cipher += current;
continue;
}
var index = 0;
index = alphabet.indexOf(current);
var shifted = (parseInt(index) + parseInt(k)) % 26;
cipher += alphabet.charAt(shifted);
}
document.getElementById("cipher-text").value = cipher;
}
function decrypt() {
var k = document.getElementById("my-key").value;
var cipher = document.getElementById("cipher-text").value;
if (!(k >= 0 && k < 26)) {
alert("Key should be between 0 and 25");
return;
}
var original = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < cipher.length; i++) {
var current = cipher.charAt(i);
if (!isLetter(current)) {
original += current;
continue;
}
var index = 0;
index = alphabet.indexOf(current);
var num = parseInt(index) - parseInt(k);
var shifted = (num + 26) % 26;
original += alphabet.charAt(shifted);
}
document.getElementById("original-text").value = original;
}
function isLetter(str) {
return str.length === 1 && str.match(/[a-z]/i);
}
</script>
<!- JS for Cypher Ends here ->
This code above only encrypts texts in lowercase
For example:
Result: Leo_123 -(with shift number of 2)-> ngq_123 -(after decryption)-> leo_123
but my expected result is:
Leo_123 -(with shift number of 2)-> Ngq_123 -(after decryption)-> Leo_123
the first part of the code is from my body tag and I am using bootstrap to make this happen
The javascript code follows the main principal but I want to modify it to get the expected results.
Make these changes:
Make alphabet a global variable that is initialised only once, and includes also the capital letters
Define a SIZE variable that is the length of this alphabet, and use that variable instead of the hard-coded 26, where ever you had used it.
Remove the statement that makes p lowercased.
Here is the adapted code:
// Make this global and add CAPITALS
var alphabet = "abcdefghijklmnopqrstuvwxyz";
alphabet += alphabet.toUpperCase();
var SIZE = alphabet.length; // Use this instead of 26
function encrypt() {
// Empty Original Text
document.getElementById("original-text").value = "";
var k = +document.getElementById("my-key").value;
var p = document.getElementById("plain-text").value;
if (!(k >= 0 && k < SIZE)) {
alert("Key should be between 0 and " + (SIZE-1));
return;
}
if (p.length === 0) {
alert("Plain Text is empty");
}
// Don't lowercase!
// p = p.toLowerCase();
var cipher = "";
for (var i = 0; i < p.length; i++) {
var current = p.charAt(i);
if (!isLetter(current)) {
cipher += current;
continue;
}
var index = alphabet.indexOf(current);
var shifted = (index + k) % SIZE;
cipher += alphabet.charAt(shifted);
}
document.getElementById("cipher-text").value = cipher;
}
function decrypt() {
var k = +document.getElementById("my-key").value;
var cipher = document.getElementById("cipher-text").value;
if (!(k >= 0 && k < SIZE)) {
alert("Key should be between 0 and " + (SIZE-1));
return;
}
var original = "";
for (var i = 0; i < cipher.length; i++) {
var current = cipher.charAt(i);
if (!isLetter(current)) {
original += current;
continue;
}
var index = alphabet.indexOf(current);
var num = index - k;
var shifted = (num + SIZE) % SIZE;
original += alphabet.charAt(shifted);
}
document.getElementById("original-text").value = original;
}
function isLetter(str) {
return str.length === 1 && str.match(/[a-z]/i);
}
<div class="container">
<div class="row">
<h1 class="mx-auto">Secured Data Cypher</h1>
</div>
<div class="row">
<h5 class="mx-auto desc"><br><br>Enter Your Desired Message which you want Encrypted <br><br> For example: ****_***123 </h5>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<h4>Plain Text</h4>
<textarea class="form-control" id="plain-text" rows="7"></textarea>
</div>
<div class="input-group mb-3">
<input type="number" min="0" max="51" class="form-control" id="my-key" placeholder="Key (Digits Only)">
<div class="input-group-append">
<button class="btn btn-outline-success" type="button" onclick="encrypt()">Encrypt</button>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<h4>Cipher Text</h4>
<textarea readonly class="form-control" id="cipher-text" rows="7"></textarea>
</div>
<button type="button" class="btn btn-outline-danger" onclick="decrypt()">Decrypt</button>
</div>
<div class="col-sm-4">
<div class="form-group">
<h4>Original Text</h4>
<textarea readonly class="form-control" id="original-text" rows="7"></textarea>
</div>
</div>
</div>
</div>

How do I get the value of the added input fields with Jquery?

I am trying to get the values from the added input fields and display it in the textarea.
The values of the input fields will be added once the codeBtn has been clicked and will add it in the textarea. I only have managed to get the values from the first input fields that has been created in HTML.
Moreover, I have tried to add the new value input fields.
let titleValue2 = $('#titleInput2').val();
let contentValue2 = $('#contentInput2').val();
totalString += (titleValue1 + contentValue1 + titleValue2 + contentValue2)
But this will give me 'undefined' when I only want to display the values of titleInput1 and contentInput1.
Basically what I'm trying is to get the values from each added input fields to the textarea.
Can anyone please help me? Thank you
Sample HTML Code:
<div class="btn-section">
<button class="addButton">+</button>
<button class="codeButton">Generate code</button>
</div>
<div class="container">
<label for="">Titel:</label>
<input type="text" id="titleInput1">
<label for="">Content:</label>
<input type="text" id="contentInput1">
</div>
<div class="newInputs">
</div>
<textarea name="" id="textInput" cols="30" rows="10"></textarea>
JQuery Code:
let inputCount = 1;
let totalString = ''
const defaultInput_firstpart = `<label for="">Titel:</label>
<input type="text" id="titleInput`
const defaultInput_secondpart = `">
<label for="">Content:</label>
<input type="text" id="contentInput`
const defaultInput_lastpart = `">`
function addNewInputs() {
$('.newInputs').append(defaultInput_firstpart + inputCount + defaultInput_secondpart + inputCount + defaultInput_lastpart)
}
function addValues() {
let titleValue1 = $('#titleInput1').val();
let contentValue1 = $('#contentInput1').val()
let titleValue2 = $('#titleInput2').val();
let contentValue2 = $('#contentInput2').val()
totalString += (titleValue1 + contentValue1 + titleValue2 + contentValue2)
}
$(document).ready(function() {
$('.addButton').on('click', function() {
inputCount++;
addNewInputs();
})
$('.codeButton').on('click', function() {
addValues();
$('#textInput').text(totalString)
})
})
Instead using dynamically created id use classes to get inputs value.
Below is the example
let inputCount = 1;
let totalString = ''
const defaultInput_firstpart = `<div class="nwlist"><label for="">Titel:</label>
<input type="text" class="titleInput" id="titleInput`
const defaultInput_secondpart = `">
<label for="">Content:</label>
<input type="text" class="contentInput" id="contentInput`
const defaultInput_lastpart = `"></div>`
function addNewInputs() {
$('.newInputs').append(defaultInput_firstpart + inputCount + defaultInput_secondpart + inputCount + defaultInput_lastpart)
}
function addValues() {
totalString = "";
$(".nwlist").each(function(){
totalString = totalString + $(this).find(".titleInput").val() + " " + $(this).find(".contentInput").val() + " ";
})
}
$(document).ready(function() {
$('.addButton').on('click', function() {
inputCount++;
addNewInputs();
})
$('.codeButton').on('click', function() {
addValues();
$('#textInput').text(totalString)
})
})
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="btn-section">
<button class="addButton">+</button>
<button class="codeButton">Generate code</button>
</div>
<div class="container">
<div class="nwlist">
<label for="">Titel:</label>
<input type="text" class="titleInput" id="titleInput1">
<label for="">Content:</label>
<input type="text" class="contentInput" id="contentInput1">
</div>
<div class="newInputs">
</div>
</div>
<textarea name="" id="textInput" cols="30" rows="10"></textarea>
</body>
</html>
Hope it will help.

Positioning of getElementById in HTML&Javascript

I'm working on a small game with multiple choices in Javascript, after I choose the answers and hit submit, at the bottom, it will show the answer of how many questions I answer correctly, and incorrectly as "You got question 1 correct", or "You got question 2 wrong". However, I'm not able to get the "You got question "" right/wrong in the position right after "Correct/Wrong Answer:". But when I tried the method of showing the score, it does work. Can someone point me a direction please? Thank you for your time of reading my post.
var firstQuestion = document.getElementsByName("firstQuestion");
var secondQuestion = document.getElementsByName("secondQuestion");
var thirdQuestion = document.getElementsByName("thirdQuestion");
var myArr = [firstQuestion, secondQuestion, thirdQuestion];
var score = 0;
var score2 = 0;
var score3 = 0;
var firstPara = document.getElementById("firstPara");
var secondPara = document. getElementById("secondPara");
function submitted() {
//for(var i = 0; i < myArr.length; i++) {
for(var o = 0; o < firstQuestion.length; o++) {
var num = o+1;
var name= "choice" + num ;
if ((document.getElementById(name).getAttribute("value") =="true") && (document.getElementById(name).checked))
{
score++;
$("#correctScore").text(score);
document.getElementById("firstPara").innerHTML =document.getElementById("firstPara").innerHTML + "You got question 1 right!<br>";
break;
}
}
if(score==0)
{
document.getElementById("secondPara").innerHTML =document.getElementById("secondPara").innerHTML + "You got question 1 wrong!<br>";;
}
//question 2
for(var o = 3; o < secondQuestion.length + 3; o++) {
var num = o+1;
var name= "choice" + num ;
if ((document.getElementById(name).getAttribute("value") =="true") && (document.getElementById(name).checked))
{
score++;
score2++;
$("#correctScore").text(score);
document.getElementById("firstPara").innerHTML =document.getElementById("firstPara").innerHTML + "You got question 2 right!<br>";
break;
}
}
if(score2==0)
{
document.getElementById("secondPara").innerHTML =document.getElementById("secondPara").innerHTML + "You got question 2 wrong!<br>";;
}
//question 3
for(var o = 6; o < thirdQuestion.length + 6; o++) {
var num = o+1;
var name= "choice" + num ;
if ((document.getElementById(name).getAttribute("value") =="true") && (document.getElementById(name).checked))
{
score++;
score3++;
$("#correctScore").text(score);
document.getElementById("firstPara").innerHTML =document.getElementById("firstPara").innerHTML + "You got question 3 right!<br>";
break;
}
}
if(score3==0)
{
document.getElementById("secondPara").innerHTML =document.getElementById("secondPara").innerHTML + "You got question 3 wrong!<br>";;
$("#correctScore").text=0;
}
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>Trivia Game</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Trivia Game</h1>
</div>
<div class="row">
<div class="col-md-12">
<div class="timeRemaining">
<p>Time Remaining:
<span id="timer"></span>
</div>
</div>
<input type="image" id="startBtn" src="assets/images/start.jpg" value="click me"/>
<br>
<div class="row">
<div class="col-md-12"></div>
<div class="questions">
What is the name of Black Panther's home?
</br>
<input id="choice1" type="radio" name="firstQuestion" value="false"><small>K'un Lun</small>
<input id="choice2" type="radio" name="firstQuestion" value="true"><small>Wakanda</small>
<input id="choice3" type="radio" name="firstQuestion" value="false"><small>Kamar Taj</small>
<br>
<br>
How did Dr Strange defeat Dormammu?</br>
<input id="choice4" type="radio" name="secondQuestion" value="false"><small>Built An Energy Prison</small></input>
<input id="choice5" type="radio" name="secondQuestion" value="true"><small>Create a Time Loop</small></input>
<input id="choice6" type="radio" name="secondQuestion" value="false"><small>Froze Time</small></input>
<br>
<br>
Which hero secretly has a family?</br>
<input id="choice7" type="radio" name="thirdQuestion" value="true"><small>Hawkeye</small></input>
<input id="choice8" type="radio" name="thirdQuestion" value="false"><small>Wakanda</small></input>
<input id="choice9" type="radio" name="thirdQuestion" value="false"><small>Kamar Taj</small></input>
</div>
</div>
</div>
<br>
<br>
<br>
<div class="row">
<div class="col-md-5"></div>
<input type="button" id="submit" value="Submit" onclick="submitted()"/>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<div id="answerScreen">
<div class="splashBox2">
<h2>Let's see how you did</h2>
<hr/>
<p id="correctScreen">Correct Answers:
<span id="correctScore"></span>
</p>
<p id="firstPara" style="font-size: 20;color: azure;margin-left: 60%;"></p>
<p id="wrongScreen">Wrong Answers:
<span id="wrongScore"></span>
</p>
<p id="secondPara" style="font-size: 20;color: azure; margin-left: 60%;"></p>
</div>
</div>
</div>
</div>
<script src="assets/javascript/app.js"></script>
</div>
</body>
</html>
After reading your clarification and perusing your code, here's what I can suggest.
<p id="correctScreen">Correct Answers:<span id="correctScore"></span></p>
<p id="" style="font-size: 20;color: azure;margin-left: 60%;"></p>
<p id="wrongScreen">Wrong Answers:<span id="wrongScore"></span></p>
<p id="secondPara" style="font-size: 20;color: azure; margin-left: 60%;"></p>
The correctScore span is where you want your "You got..." text to appear, and you could accomplish this by simply replacing $("#correctScore").text(score); with $("#correctScore").text("You got question 1 right"); (And obviously you'd want to rename your elements and variables so they make sense with the replacement.)
The only issue is that the next line of text (the text for question 2) would be vertically aligned with "Correct answers" instead of with the question 1 text. The simplest way to fix this (and not really a professional way) would be to add a bunch of &nbsp characters to indent your text. Below are some other (better) options.
Using just HTML markup, you could replace the span with a block element, like a div (and change your correctScreen from being a p to being a div to make this work). The catch is that switching to a block element also means the contents would start on a new line, so they wouldn't be next to "Correct answers:" as you would like -- unless you styled the block element with float: left (and made the other changes that go along with this, such as specifying a width attribute for your divs.)
Or since your page has bootstrap, you could avoid handling (some of) these details yourself and get two divs to appear side-by-side by doing something like this:
<div class="row">
<div class="col-md-4" id="spacer"></div>
<div class="col-md-4" id="correctAnswersIntro">Correct answers:</div>
<div class="col-md-4" id="correctAnswersList">You got question 1 right<br></div>
</div>
There are few issue that is needed to be corrected in your code.
Firstly, the JavaScript snippet has a syntax error, where the last brace is missing. I assume that it's a mistake while copying it here.
Secondly, you are using the mix of JavaScript API and jQuery to access DOM elements. If you stick to one, it will be cleaner and the code will be easier to read. Please see below.
...
var firstQuestion = $('[name="firstQuestion"]');
var secondQuestion = $('[name="seconQuestion"]');
var thirdQuestion = $('[name="thirdQuestion"]');;
var score = 0;
var score2 = 0;
var score3 = 0;
var firstPara = $("#firstPara");
var secondPara = $("#secondPara");
function submitted() {
for (var o = 0; o < firstQuestion.length; o++) {
var num = o + 1;
var name = "choice" + num;
if (($('#' + name).getAttribute("value") == "true") && ($('#' + name).checked))
{
score++;
$("#correctScore").text(score);
$("#firstPara").html($("#firstPara").html() + "You got question 1 right!<br>");
break;
}
}
if (score == 0)
{
$("#secondPara").html($("#secondPara").html() + "You got question 1 wrong!<br>");
}
//question 2
for (var o = 3; o < secondQuestion.length + 3; o++) {
var num = o + 1;
var name = "choice" + num;
if (($('#' + name).getAttribute("value") == "true") && ($('#' + name).checked))
{
score++;
score2++;
$("#correctScore").text(score);
$("#firstPara").html($("#firstPara").html() + "You got question 2 right!<br>");
break;
}
}
if (score2 == 0)
{
$("#secondPara").html($("#secondPara").html() + "You got question 2 wrong!<br>");
;
}
//question 3
for (var o = 6; o < thirdQuestion.length + 6; o++) {
var num = o + 1;
var name = "choice" + num;
if (($('#' + name).getAttribute("value") == "true") && ($('#' + name).checked))
{
score++;
score3++;
$("#correctScore").text(score);
$("#firstPara").html($("#firstPara").html() + "You got question 3 right!<br>");
break;
}
}
if (score3 == 0)
{
$("#secondPara").html($("#secondPara").html() + "You got question 3 wrong!<br>");
;
$("#correctScore").text(0);
}
}
...
Please post the full HTML code here, so that it would be easier to correct it.

How do I make separate characters in a string random fonts?

I'm currently trying to write a block of Javascript in my webpage that takes text from a text area and converts each individual character in the string into a random font.
This is my current attempt (which doesn't work):
<body>
<div class="container main-form">
<form>
<div class="form-group">
<label for="textinput">Input your text below</label>
<textarea class="form-control" id="textinput" rows="3"></textarea>
</div>
<button type="button" class="btn btn-outline-primary float-right" id="submit">Generate</button>
</form>
</div>
<div class="container output">
<script>
var input = "";
var ouput = "";
var inputarr = [];
// Array of fonts for span
var fontarr = ["font-family: MaxHand1, sans-serif", "font-family: MaxHand2, sans-serif", "font-family: MaxHand3, sans-serif"];
if document.getElementById('submit').clicked == true { // If button is clicked
input = document.getElementById('textinput'); // Set 'input' string to what was in the text area
inputarr = input.split(""); // Create an array of letters from input
for (i = 0; i < inputarr.length; i++) {
fontchange = fontarr[Math.floor((Math.random() * 3) + 1)]; // Choose a random font
output = (output + "<span style=\"" + fontchange + "\">" + inputarr[i] + "</span>"); // Add <span style="[fontchange]">inputarr[i]</span> to output string
}
document.getElementById(textoutput) = output; // Output string to line 45
}
</script>
<p id="textoutput"></p>
</div>
</body>
When I click submit, though, nothing appears on screen. I'm not sure if it's just because the string isn't being changed, or if it's just not updating the textoutput p tags.
There are couples of syntax errors in your code. document.getElementById('submit').clicked == true and document.getElementById(textoutput) = output and input = document.getElementById('textinput') <--- this will not return string(it will return whole tag). Try below code(I fixed error)
those changes from the previous answer plus you need to modify your Math.random call so you get 0,1,2 --> I did this using the % (mod) operator
var fontarr = ["font-family: courier new, sans-serif",
"font-family: comic sans, sans-serif",
"font-family: arial black, sans-serif"];
function change(){
var input = "";
var output = "";
input = document.getElementById('textinput').value;
for (i = 0; i < input.length; i++) {
fontchange = fontarr[Math.floor(((Math.random() * 3) + 1)%3)];
output += "<span style=\"" + fontchange + "\">" + input[i] + "</span>";
}
//console.log(output);
document.getElementById("textoutput").innerHTML = output;
}
<body>
<div class="container main-form">
<form>
<div class="form-group">
<label for="textinput">Input your text below</label>
<textarea class="form-control" id="textinput" rows="3"></textarea>
</div>
<button type="button" class="btn btn-outline-primary float-right" id="submit" onclick="change()">Generate</button>
</form>
</div>
<div class="container output">
<script>
</script>
<p id="textoutput"></p>
</div>
</body>

HTML, JS - Display Loop's Output By Calling <div> From HTML To JS

I have a situation where user may insert the Total Quantity and also the Total Pass and Total Fail. I have created a function where when the number of Total Pass inserted, the loop (of entering the pass score) will run according to the iterations inputted.
However, I do not want to have the loop to display the line Enter The Score : in the JavaScript function. Therefore, I want the function to call a div from the HTML itself.
For example, I want the <div id="outputPass"><p>Enter the score : <input type="text" /></p></div> to be called in the loop function which I have created in the document.getElementById('btnPass').onclick = function().
I have inserted some comments in the code section.
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" />&nbsp<input type="button" value="Key In Score" id="btnPass" onclick="return validate();"></p><br />
<!--This Div-->
<div id="outputPass">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" />&nbsp<input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>
You can make the following changes to achieve what you are looking for:
Initially we're giving an id of pscore/fscore (for pass and fail respectively) to the <p></p> tags and hiding them.
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
We're accessing them in the javascript code in the form of variables pscore and fscore respectively. (Make sure they are declared globally outside)
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
Then in the iterations we can just make a clone of the pscore/fscore , give a class of pscore/fscore to the <p></p> tags and remove the id of pscore/score (to avoid duplicate IDs), changing the display to block and append it to the output container by using the following:
var cln = pscore.cloneNode(true);
cln.style.display="block";
cln.className ="pscore";
cln.removeAttribute("id");
item.appendChild(cln);
var cln = fscore.cloneNode(true);
cln.style.display="block";
cln.removeAttribute("id");
cln.className ="fscore";
item.appendChild(cln);
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = pscore.cloneNode(true);
cln.style.display = "block";
cln.className = "pscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = fscore.cloneNode(true);
cln.style.display = "block";
cln.className = "fscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" /> <input type="button" value="Key In Score" id="btnPass"></p><br />
<!--This Div-->
<div id="outputPass">
<p id="pscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" /> <input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>

Categories

Resources