JavaScript: textarea not showing output - javascript

I am making a Leetspeak converter program, but the second textarea does not show any output. Here is my rudimentary code:
<!DOCTYPE html>
<html>
<body>
<h1>Leetspeak Converter</h1>
<script language="JavaScript">
function convert(){
var x = document.getElementById("myTextArea").value;
var result='';
for (var i = 0, len = x.length; i < len; i++) {
if (x.charAt(i)=='A'){
result = result + '4';
}
}
document.getElementById('resultTextarea').value = result ;
}
</script>
<div class="input">
<textarea id = "myTextArea" rows = "6" cols = "80">
</textarea>
</div>
<div class="push">
<button onclick="convert">Convert</button>
</div>
<div class="result">
<textarea id = "resultTextArea" rows = "6" cols = "80">
</textarea>
</div>
It does not produce any output at all. I have tried using console.log(), but it shows no output.
I have also used a debugger, but no dice.

You have syntax errors, in 2 parts, so change this
<button onclick="convert">Convert</button> // this does not represent a method
with this
<button onclick="convert()">Convert</button>
and in addition, this
document.getElementById('resultTextarea').value = result ; // a small typo in id
with this
document.getElementById('resultTextArea').value = result ;
function convert(){
var x = document.getElementById("myTextArea").value;
var result=0;
for (var i = 0, len = x.length; i < len; i++) {
if (x.charAt(i)=='A'){
result = result + 4;
}
}
document.getElementById('resultTextArea').value = result ;
}
<div class="input">
<textarea id = "myTextArea" rows = "6" cols = "80">
</textarea>
</div>
<div class="push">
<button onclick="convert()">Convert</button>
</div>
<div class="result">
<textarea id = "resultTextArea" rows = "6" cols = "80">
</textarea>
</div>

You have syntax error in:
<button onclick="convert">Convert</button>
Fixed this as:
<button onclick="convert()">Convert</button>

try this
<!DOCTYPE html>
<html>
<body>
<h1>Leetspeak Converter</h1>
<script language="JavaScript">
function convert(){
var x = document.getElementById("myTextArea").value;
var result='';
for (var i = 0,len = x.length ; i < len; i++) {
if (x.charAt(i)=='A'){
result = result + '4';
}
}
document.getElementById('resultTextArea').value = result ;
}
</script>
<div class="input">
<textarea id = "myTextArea" rows = "6" cols = "80">
</textarea>
</div>
<div class="push">
<button onclick="convert()">Convert</button>
</div>
<div class="result">
<textarea id = "resultTextArea" rows = "6" cols = "80">
</textarea>
</div>
</body>
</html>

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 make a dynamic drop down menu using JavaScript

I have it so you type in on a form a maximum number then it creates a table after clicking a button.
I want it so after you click the button to add the row it writes a drop down menu in the table that goes from 0 to the number you put in the form
This is my HTML code:
<html>
<head>
<title>Form Generator</title>
<link rel="stylesheet" type="text/css" href="../css/converter.css"/>
<script language="JavaScript" src="../js/exercise2.js" type="text/javascript">
</script>
</head>
<body>
<p>
<button class="button" data-modal="M2KM">Form Generator</button>
</p>
<div id="M2KM" class="modal">
<div class="modal-content">
<div class="form">
<a class="close">×</a>
<form action="">
<textarea rows="1" name="Section" id="Section" cols="10">Section</textarea>
<textarea rows="1" name="Max" id="Max" cols="10">Max</textarea>
<textarea rows="1" name="Comment" id="Comment" cols="10">Comment</textarea>
<textarea rows="1" name="Mark" id="Mark" cols="10">Mark</textarea>
<input type="button" value="Add Row" name="Add Row" onclick="conversionTable('table')" />
<input type="reset" value="Clear" name="Clear">
</form>
<div id="conversion">
<table id="table">
<thead>
<tr>
<th>Section</th>
<th>Max</th>
<th>Comment</th>
<th>Mark</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
This is my JavaScript Code:
function conversionTable(tagId, from, to)
{
var section = document.getElementById("Section").value;
var max = document.getElementById("Max").value;
var comment = document.getElementById("Comment").value;
var mark = document.getElementById("Mark").value;
from = 0;
to = 1;
var total = 0;
var arr = [];
var conv = document.getElementById(tagId) ;
var pre = document.createElement("pre");
conv.appendChild(pre);
var body= conv.appendChild(document.createElement("tbody"));
for (var i=from; i<to; i++)
{ row = body.appendChild(document.createElement("tr"));
var data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(section));
data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(max));
var data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(comment));
data=row.appendChild(document.createElement("select"));
data.setAttribute("id", "mySelect");
row.appendChild(data);
var z = document.createElement("option");
z.setAttribute("value", "volvocar");
var t = document.createTextNode("1");
z.appendChild(t);
document.getElementById("mySelect").appendChild(z);
total = total + mark;
var obj = {section: section, max: max, comment: comment, mark: mark};
arr.push(obj);
}
}
This is a screenshot showing test data:
Here's a simplified example that adds a select element with a number of options equal to the number entered by the user.
See comments in the code for an explanation of how it works.
// Identifies existing HTML elements
const maxInput = document.getElementById("max");
const button = document.getElementById("button");
const table = document.getElementById("table");
// Calls `addDropdown` when `button` is clicked
button.addEventListener("click", addDropdown);
// Defines the event listener
function addDropdown(event) { //(`event` object is available if we want it)
// Gets value from input
let max = parseInt(maxInput.value);
// Exits function early if maxInput doesn't have a number
if(!max){ return; }
// Defines the new elements
const row = document.createElement("tr");
const cell = document.createElement("td");
const dropdown = document.createElement("select");
// Enumerates options and adds them to the select element
let optNumber = -1;
while(++optNumber <= max){
let optionElement = document.createElement("option");
optionElement.value = "opt" + optNumber;
optionElement.innerHTML = "Option " + optNumber;
dropdown.appendChild(optionElement);
}
// Adds the elements to the page
cell.appendChild(dropdown);
row.appendChild(cell);
table.appendChild(row);
}
<label>
<span>Enter maximum value for dropdown:</span>
<input id="max" value="5" />
</label>
<br />
<button id="button">Add Dropdown in New Row</button>
<div id="container">
<table id="table"></table>
</div>

cloneNode and total the value of all nodes (parent+childs). Javascript

I want to total the values of all input, but in the beginning there's only one input element and you add the clone(s) with a button. Actually I have two issues:
1. How to place the clone node always under the node before it.
2. How to total the values of all nodes.
Here's the code:
function nambahData() {
var a = document.getElementById("harga");
var b = a.cloneNode(false);
document.getElementById("form").appendChild(b);
}
function ditotal() {
var x = document.getElementById("harga").value;
var y = document.getElementById("harga").childNode.value;
document.getElementById("total").value = parseInt(x) + parseInt(y);
}
</script>
<div id="form">
<input id="harga" type=number>
<br>
</div>
<button onclick="nambahData()">add data</button>
<br>
<button onclick="ditotal()">total all</button>
<input id="total" type=number>
Hope this helps you ..
window.nambahData = function() {
var a = document.getElementsByName("harga");
var b = a[0].cloneNode(false);
document.getElementById("form").appendChild(b);
}
window.ditotal = function() {
var totalItems = 0;
for(i=document.getElementsByName("harga").length-1;i>=0;i--)
{
var item = document.getElementsByName("harga")[i];
totalItems += parseFloat(item.value);
}
document.getElementById("total").value = totalItems;
}
.inputStyle{
display:block;
}
<div id="form">
<input name="harga" type="number" class="inputStyle">
</div>
<button onclick="nambahData()">add data</button>
<br>
<button onclick="ditotal()">total all</button>
<input id="total" type=number>

Dynamic Javascript Div

Got JS Fiddle to work
http://jsfiddle.net/pskjxofo/
Attached I have the following function, the purpose of which is to perform basic calculation. I also added a feature for adding more boxes for calculation. What I am currently stuck on is how to tell Javascript to make dynamic divs, and how to tell it to perform the same calculations for each line every time I click on Calculate. Assistance on this would be greatly appreciated. Thank you all in advance.
<div id="redo">
2 X
<input type="text" id="initial">
= <input type="text" id="solved">
<input type="submit" value="Calculate" onclick="calculait()">
<input type="submit" value="Add Another Box" onclick="addmore()">
</div>
<div id="main"></div>
<script type="text/javascript">
function calculait(){
var first = document.getElementById('initial');
var second = document.getElementById('solved');
second.value = first.value * 2;
}
function addmore(){
var bar = document.getElementById('main');
bar.innerHTML = bar.innerHTML + "<div id='redo'>2 X
<input type='text' id='initial'> = <input type='text' id='solved'>
<input type='submit' value='Calculate' onclick='calculait()'
<input type='submit' value='Add Another Box' onclick='addmore()";
}
</script>
Here is one of the many ways to do it. You could have this HTML structure:
<div id="main">
<div class="operation">
2 X <input type="text" class="initial"/>=
<input type="text" class="solved"/>
</div>
</div>
<input type="submit" value="Calculate" onclick="calculait()"/>
<input type="submit" value="Add Another Box" onclick="addmore()"/>
And this JS:
// Main container for all operations
var main = document.getElementById('main');
// Piece of HTML you'll be duplicating
var op = document.getElementsByClassName('operation')[0].outerHTML;
function calculait() {
// Get every operation div
var operations = document.getElementsByClassName('operation');
// For each of them, calculate
for(var i=0, l=operations.length; i<l; i++){
operations[i].getElementsByClassName('solved')[0].value =
parseFloat(operations[i].getElementsByClassName('initial')[0].value) * 2;
}
}
function addmore() {
main.insertAdjacentHTML('beforeend',op);
}
JS Fiddle Demo
If I understood correctly, I think this code will help.
First of all, change your ids for classes (IDs must be always unique in the page).
<input type="text" class="initial">
<input type="text" class="solved">
And in the JS, you use a for to iterate for this elements.
function calculait() {
var initial = document.getElementsByClassName('initial');
var solved = document.getElementsByClassName('solved');
for (var i = 0; i < initial.length; i++) {
solved[i].value = initial[i].value * 2;
}
}
function addmore() {
var bar = document.getElementById('main');
var html = "<div>2 X ";
html += "<input type='text' class='initial'> = ";
html += "<input type='text' class='solved'>";
html += "</div>";
bar.innerHTML = bar.innerHTML + html;
}
JSFiddle: http://jsfiddle.net/pskjxofo/2/
Give it a try and let me know if it helps!
When you write JavaScript use a debugger, your code didn't parse. You can find one in your browser by hitting F12.
Don't repeat yourself. A clean solution is to put html to duplicate into a template or similar and call a function to copy it.
Use input type=number for numbers.
<html>
<meta charset="utf-8">
<template id="calculate_template">
<form id="" class="calculate_form">
<input value="2" type="number" name="initial_1"> X
<input type="number" name="initial_2"> =
<input type="number" name="solved" disabled="disabled" >
</form>
</template>
<div id="main">
<button onclick="addmore();">Add Another Box</button>
<button onclick="calculate();">Calculate</button>
</div>
<script type="text/javascript">
function calculate(){
/*Calculates all*/
var forms = document.getElementsByClassName('calculate_form'),
i,
length = forms.length;
for(i = 0; i < length; i++){
console.log(forms[i]);
forms[i]['solved'].value = forms[i]['initial_1'].value * forms[i]['initial_2'].value;
}
}
function addmore(){
var main = document.getElementById('main');
main.insertAdjacentHTML("beforeend", document.getElementById('calculate_template').innerHTML);
}
addmore();
</script>
</html>
Demonstration
Here's a way of doing it:
var counter = 0;
function calculait(calculationId) {
var first = document.getElementById('initial' + calculationId);
var second = document.getElementById('solved' + calculationId);
second.value = first.value * 2;
}
function addmore() {
counter++;
var bar = document.getElementById('main');
var newDiv = document.createElement("div");
newDiv.id = "redo" + counter;
newDiv.innerHTML = "2 X <input type='text' id='initial" + counter + "'/> = <input type='text' id='solved" + counter + "'/><input type='submit' value='Calculate' onclick='calculait(" + counter + ")'/><input type='submit' value='Add Another Box' onclick='addmore(" + counter + ")'/>";
bar.appendChild(newDiv);
}
<div id="main"><div id="redo0">2 X <input type="text" id="initial0" /> = <input type="text" id="solved0" /><input type="button" value="Calculate" onclick="calculait(0)" /><input type="button" value="Add Another Box" onclick="addmore(0)" /></div>
</div>
HTML
<p id="operations"></p>
<p>
<input type="submit" value="Calculate" onclick="calc()" />
<input type="submit" value="Add operation" onclick="addOp()" />
</p>
Javascript
var id = 0, multiplier = 2;
var operations = document.getElementById('operations');
function addOp() {
++id;
var p = document.createElement("p");
var right = document.createElement("input");
right.id = 'right_' + id;
right.type = 'text';
var result = document.createElement('input');
result.id = 'result_' + id;
right.type = 'text';
p.innerHTML = multiplier + ' x ';
p.appendChild(right);
p.innerHTML += ' = ';
p.appendChild(result);
operations.appendChild(p);
}
function calc() {
for(var i = 1; i <= id; i++) {
var right = document.getElementById('right_' + i);
var result = document.getElementById('result_' + i);
result.value = multiplier * right.value;
}
}
addOp();
JSFiddle : http://jsfiddle.net/0Lcg0pyz/

Please help me fix this javascript tool

This is in the head :
<script language="javascript" type="text/javascript"> f
function TextDefine(val) {
var i= 0;
var array1 = val.value.split("\n");
for ( i = 0; i < array1.length; ++i) {
array1[i] = "[b]" + array1[i] + "[/b]";
}
document.getElementById('another').value = array1.join("\n");
}
</script>
Then This is in the body:
<textarea name="data" id="data"></textarea>
<textarea name="another" id="another"></textarea>
<input type="button" name="submit1" value="Submit"
onclick="TextDefine(document.getElementById('data'))" />
i would like to add another text area so that when i click on the generate button, it will also get the content of the text area i just created. example:
text area 1
content of the text area 1
text area i just created
content of the text area 2
then the generated content content in the thrid text area should be:
[b]content of the text area 1[/b]
content of the text area 2
please see the javascript code why it had [b], i do not know how do to it so i need your help :( Thank You!
Is the keyword function being split onto two words something to do with entering it into stackoverflow? The below works for me:
<html>
<head>
<script language="javascript" type="text/javascript"> function TextDefine(val){ var i= 0; var array1 = val.value.split("\n"); for ( i = 0; i < array1.length; ++i) { array1[i] = " [b]" + array1[i] + "[/b]"; } document.getElementById('another').value = array1.join("\n"); }</script>
</head>
<body>
<form>
<textarea name="data" id="data"></textarea>
<textarea name="another" id="another"></textarea>
<input type="button" name="submit1" value="Submit" onclick="TextDefine(document.getElementById('data'))" />
</form>
</body>
</html>
Is this what you want to do?
http://jsbin.com/eligo4/edit
<script language="javascript" type="text/javascript">
function TextDefine(val, anotherval){
var i= 0;
var array1 = val.value.split("\n");
for ( i = 0; i < array1.length; ++i) {
array1[i] = "[b]" + array1[i] + "[/b]";
}
document.getElementById('generate').value = array1.join("\n")+"\n"+ document.getElementById('another').value;
}
</script>
<textarea name="data" id="data"></textarea>
<textarea name="another" id="another"></textarea>
<textarea name="generate" id="generate"></textarea>
<input type="button" name="submit1" value="Submit" onclick="TextDefine(document.getElementById('data'), document.getElementById('another'))" />

Categories

Resources