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

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>

Related

How can I prevent my program from converting selected number which starts with 0 to octal value using javascript?

When I select a number that starts with 0, such a number is converted to its octal form which I don't want but works perfectly well for those that didn't start with 0. Attached is pictures explaining what I mean.
Before Selection of Number starting with 0
After Selection of Number starting with 0
From the picture you can see 0703 got converted to 451. How can I stop this.
let phoneNumberSelector = document.querySelector("#phone");
const mtnNumber = ['703', '706', '803', '806', '810', '813', '814', '816', '903', '906', '913', '0703', '0706'];
phoneNumberSelector.addEventListener('keyup', (e) => {
removeElements();
for (let i of mtnNumber) {
// i = i.toString();
if (i.startsWith(phoneNumberSelector.value) && phoneNumberSelector.value != '') {
let listItem = document.createElement("li");
listItem.classList.add('list-items');
listItem.style.cursor = 'pointer';
listItem.setAttribute('onclick', "displayNames(" + i + ")")
let word = "<b>" + i.slice(0, phoneNumberSelector.value.length) + "</b>";
word += i.slice(phoneNumberSelector.value.length);
listItem.innerHTML = word;
document.querySelector('.list').appendChild(listItem);
}
}
})
function displayNames(param) {
phoneNumberSelector.value = param;
removeElements();
}
function removeElements() {
let items = document.querySelectorAll('.list-items')
items.forEach((element) => {
element.remove();
});
}
<section class="section1"></section>
<section class="section2">
<div class="reg-form">
<form action="" method="">
<div class="form-container">
<h1 style="text-align: center;">Phonie</h1>
<div class="input-reg email-input">
<label for="username">Username</label>
<input id="username" type="text" name="username">
</div>
<div class="list-div">
<ul class="list"></ul>
</div>
<div class="input-reg email-input">
<label for="phone">Phone Number</label>
<input id="phone" type="text" name="phone">
</div>
<div class="input-reg email-input">
<input class="submit-btn submit-btn2" type="submit" value="Check Number">
</div>
</div>
</form>
</div>
</section>
The numbers are getting converted to octal because you are passing the number (of type string) to the displayNames function as a number (without quotes).
This is the offending line:
listItem.setAttribute('onclick', "displayNames(" + i + ")")
with the value of i set to "0703", the value for onclick becomes "displayNames(0703)".
You can fix this by adding quotes around the i variable in the string passed as onclick.
For example:
listItem.setAttribute('onclick', "displayNames('" + i + "')");
or with a string template to make it a bit easier to read:
listItem.setAttribute('onclick', `displayNames("${i}")`);

How to empty div tag filled by javascript

I have a script where a user enters text into an input box and it displays the text in different fonts as they type in a div below (#Output).
My problem is if a user deletes the text in the input box, the div tag that gets populated is left with all the non dynamic data, how can I can I completely empty the div (in this case #Output) when there is nothing in the input.
<script>
$(document).ready(function(){
$("#UpdateText").keyup(function(){
// Getting the current value of textarea
var currentText = $(this).val();
// set font variables
var text = "";
var i;
for (i = 1; i < 30; i++) {
// Setting the font of Div content
text += "<div>Font-" + i + " : <span id=\"fontResult\" style=\"font-family:Font-" + i + "\">" + currentText + "</span></div>";
}
$('#Output').html(text);
});
});
</script>
<div class="content">
<label for="UpdateText">Enter the text you would like here, then select your font</label>
<br />
<textarea id="UpdateText" rows="1" cols="30" style="resize: none; text-align: center" placeholder="Type the name/word here..."></textarea>
<br />
<br />
<div id="Output"></div>
<!-- end .content -->
</div>
Fastest without any other change:
$('#Output').html(currentText ? text : "");
$(document).ready(function() {
$("#UpdateText").keyup(function() {
// Getting the current value of textarea
var currentText = $(this).val();
// set font variables
var text = "";
var i;
for (i = 1; i < 30; i++) {
// Setting the font of Div content
text += "<div>Font-" + i + " : <span id=\"fontResult\" style=\"font-family:Font-" + i + "\">" + currentText + "</span></div>";
}
$('#Output').html(currentText ? text : "");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
<label for="UpdateText">Enter the text you would like here, then select your font</label>
<br />
<textarea id="UpdateText" rows="1" cols="30" style="resize: none; text-align: center" placeholder="Type the name/word here..."></textarea>
<br />
<br />
<div id="Output"></div>
<!-- end .content -->
</div>
Updated version to ES6 and not do anything on empty string
$(function() {
$("#UpdateText").on("input", function() {
$('#Output').empty();
// Getting the current value of textarea
const currentText = $(this).val().trim();
if (currentText) {
// set font variables
const text = [...Array(31).keys()].slice(1)
.map(i => `<div>Font-${i}: <span id="fontResult" style="font-family:Font-${i}">${currentText}</span></div>`);
$('#Output').html(text);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
<label for="UpdateText">Enter the text you would like here, then select your font</label>
<br />
<textarea id="UpdateText" rows="1" cols="30" style="resize: none; text-align: center" placeholder="Type the name/word here..."></textarea>
<br />
<br />
<div id="Output"></div>
<!-- end .content -->
</div>
Can you please try running the snippet below if this is what you are trying to achieve.
$(document).ready(function(){
$("#UpdateText").keyup(function(){
// Always initialize the display
$('#Output').html('');
// Getting the current value of textarea
var currentText = $(this).val();
// set font variables
//check if the textbox is empty (removes the leading and trailing spaces) prevents 30 loops of iteration if empty
if(currentText.trim() != ''){
var text = "";
for (i = 1; i < 30; i++) {
// Setting the font of Div content
text += "<div>Font-" + i + " : <span id=\"fontResult\" style=\"font-family:Font-" + i + "\">" + currentText + "</span></div>";
}
$('#Output').html(text);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
<label for="UpdateText">Enter the text you would like here, then select your font</label>
<br />
<textarea id="UpdateText" rows="1" cols="30" style="resize: none; text-align: center" placeholder="Type the name/word here..."></textarea>
<br />
<br />
<div id="Output"></div>
<!-- end .content -->
</div>

Generate Header for txt file

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.

Checking if a new line exist using regex

I am writing a javascript to add {y} at the start and {/y) at the end to non english characters. I also need it to leave empty lines as it is. But in the current scenario, it is adding {y}{/y) to empty lines/new lines.
var lyrics = document.getElementById('userInput');
function printSong() {
var input = lyrics.value;
var lines = input.split('\n');
var generatedText = "";
for (var i = 0; i < lines.length; i++) {
if (lines[i].match(/[A-z]|[0-9]{2}/) != null | lines[i].match(/\s/) != null) {
generatedText = generatedText + lines[i] + '\n';
} else {
generatedText = generatedText + "{y}" + lines[i] + "{/y}" + '\n';
}
}
document.getElementById('output').value = generatedText;
}
<div class="container-fluid">
<div class="col-xs-12">
<div class="col-xs-5">
<textarea id="userInput" class="form-control" cols="40" rows="10" placeholder="Enter song lyrics here">testing
அஇஉ்உ்உ</textarea>
</div>
<div class="col-xs-2" style="text-align: center">
<button type="button" class="btn btn-success" onclick="printSong()">Generate tags</button>
</div>
<div class="col-xs-5">
<textarea disabled id="output" class="form-control" cols="40" rows="10" placeholder="Generated Song"></textarea>
</div>
</div>
</div>
Avoiding adding your markers to blank lines is simply a matter of adding
!lines[i].trim() ||
...to the beginning of your if. That takes the line, strips any leading and trailing whitespace from it, and sees if the result is empty. ("" is a falsy value, so !"" is true.) If it is blank, it skips the regex check (because || short-circuits if the left-hand operand is truthy) and we go into the if block (so we don't add markers to blank lines).
But as Wiktor pointed out:
For the logical OR operation, it's ||, not |
[A-z] matches all characters between upper case A and lower case z. There are many characters after Z and before a that will also be matched.
Also: [A-z]|[0-9]{2} means "a single character A through z or two digits." If that's what you really meant, fine, but if you meant "two characters which are either A through z or 0 through 9" you'd combine them into a single character class. I haven't done that below, on the theory you may want the condition the way it is.
And finally: If all you want to do is check if a string matches an expression, you don't want match; instead, use test on the expression. E.g.
if (string.match(expression) != null)
becomes
if (expression.test())
That lets the regular expression engine stop as soon as it knows the result and not bother to build the result array.
With those changes:
var lyrics = document.getElementById('userInput');
function printSong() {
var input = lyrics.value;
var lines = input.split('\n');
var generatedText = "";
for (var i = 0; i < lines.length; i++) {
if (!lines[i].trim() || /[a-zA-Z]|[0-9]{2}/.test(lines[i]) || lines[i].match(/\s/) != null) {
generatedText = generatedText + lines[i] + '\n';
} else {
generatedText = generatedText + "{y}" + lines[i] + "{/y}" + '\n';
}
}
document.getElementById('output').value = generatedText;
}
<div class="container-fluid">
<div class="col-xs-12">
<div class="col-xs-5">
<textarea id="userInput" class="form-control" cols="40" rows="10" placeholder="Enter song lyrics here">testing
அஇஉ்உ்உ</textarea>
</div>
<div class="col-xs-2" style="text-align: center">
<button type="button" class="btn btn-success" onclick="printSong()">Generate tags</button>
</div>
<div class="col-xs-5">
<textarea disabled id="output" class="form-control" cols="40" rows="10" placeholder="Generated Song"></textarea>
</div>
</div>
</div>

Loading Values into auto generated HTML input elements using javascript

I am using a javascript function to populate html element generated automatically after submitting a form from a different div.
Here is the html:
<html >
<body>
<div class="wrapper">
<div id="one">
<form name="form">
<fieldset>
<legend>BILLING</legend>
<div> <label for="ex1">Procedure/Drug</label>
<input type="text" name="procdrug" id="procdrug"/><br><br>
<label>Amount</label>
<input type="text" name="amount" id="amount"/><br><br>
<input type="button" onclick="addInput()" name="add" value="Add input field" style="margin-left:150px" />
</div>
</fieldset>
</form>
</div>
<div id="two">
<fieldset>
<legend>TN QUEUE</legend>
<label><B>Procedure/Drug</b></label><label><b>Amount</b></label><br>
<div id="text">
</div>
<label><b>Total</b></label>
<input type="text" name="total" id="total"/>
</fieldset>
</div>
</body>
</html>
Here is the javascript function
<script language="javascript">
fields = 0;
function addInput() {
var amount=document.getElementById('amount').value;
var pd=document.getElementById('procdrug').value;
if (fields != 10)
{
document.getElementById('text').innerHTML += "<input id='pdgen' type='text'/>";
document.getElementById('text').innerHTML += "<input id='amtgen' type='text'/><br />";
document.getElementById('pdgen').value=pd;
document.getElementById('amtgen').value=amount;
fields += 1;
}
else
{
document.getElementById('text').innerHTML += "<br />Only A Maximum of 10 is allowed.";
document.form.add.disabled=true;
}
}
</script>
The generated elements values are posted from the form and increment on every submit. My problem is the only on submit first element is updated with the new value:
Sample results
Procedure/Drug Amount
Amoxyl 200
blank element blank element
blank element blank element
blank element blank element
Total
The problem is you are adding your elements with the .innerHtml += method which is avoiding the values entered before. You need to use appendChild method to add new elements. Here is your new code :
fields = 0;
function addInput() {
var amount=document.getElementById('amount').value;
var pd=document.getElementById('procdrug').value;
var br = document.createElement('br');
if (fields != 10)
{
var input1 = document.createElement('input');
input1.setAttribute('id','pdgen' + fields);
input1.value = pd;
var input2 = document.createElement('input');
input2.setAttribute('id','amtgen' + fields);
input2.value = amount;
document.getElementById('text').appendChild(input1);
document.getElementById('text').appendChild(input2);
document.getElementById('text').appendChild(br);
fields++;
}
else
{
document.getElementById('text').innerHTML += "<br />Only A Maximum of 10 is allowed.";
document.form.add.disabled=true;
}
}
FIDDLE

Categories

Resources