How to write the code in "function printOut(){} " in javascript? - javascript

I need help with how to code this program in javascript. The javascript code should load a character from a box and a number (N) from another box. When you press a button, N rows prints each one of those with N characters (same characters that are loaded are printed). Before printing, check that it is only available a character in the box where characters are to be entered.
code in html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="theText"></p>
<p id="theNumber"></p>
a charachter: <input type="charachter" id="theChar">
a number: <input type="number" id="theNbr">
<button onclick="printOut()">print out!</button>
<script type="text/javascript" src="script.js" ></script>
</body>
</html>
Code in Javascript:
function printOut(){
var theText = document.getElementById("theText").innerHTML;
document.getElementById("theText").innerHTML=
document.getElementById("theChar").value;
var theNumber = document.getElementById("theNbr").innerHTML;
document.getElementById("theNumber").innerHTML=
document.getElementById("theNbr").value;
var newText= theText;
var outPut;
for(i = 0; i<theNumber; i++){
newText =newText + theText;
}
newText = newText + "<br>";
for( i = 0; i< theNumber; i++){
outPut = outPut + newText;
}
document.getElementById("theText").innerHTML= outPut;
}

There are several issues in your code, even after the corrections you made after comments were made. Some of the more important:
Don't use innerHTML on an input element. It makes no sense. To get its value, use value.
Don't assign to document.getElementById("theNumber").innerHTML: it will replace any HTML you already had, and thus will remove the theNbr input. Any reference to it will fail with an error from now on.
Initialise your variables before reading from them. outPut is never initialised and so outPut + newText will give undesired results.
Although your can do this with for loops, there is a nice string method in JavaScript with which you can repeat a character or even a longer string: repeat.
Here is how it could work:
function printOut(){
var theNumber = document.getElementById("theNbr").value; // Don't use innerHTML
var theChar = document.getElementById("theChar").value;
var oneLine = theChar.repeat(theNumber) + "<br>";
var output = oneLine.repeat(theNumber);
document.getElementById("theText").innerHTML = output;
}
a charachter: <input type="charachter" id="theChar">
a number: <input type="number" id="theNbr">
<button onclick="printOut()">print out!</button>
<p id="theText"></p>

Related

Javascript library to compare 2 html string like freecodecamp

I have a project where we have a compare the original code and code written by the user. The user can code and then on button click we have to compare the written code with original code.
I have both original and new code in string
originalHtml : <html><body style='color:white;background:purple;'></body></html>
newHtml : <html> <body style="background:purple;color:white;"> </body> . </html>
Here there are 3 things to keep in mind
1) White space (should not show the difference for white space)
2) ' and " (should not compare quotes, both are valid in HTML)
3) Attribute order (should show difference only for missing attribute, ignore attributes order)
Any suggestions or alternative solution will be appreciated.
I have created a code pen for you, this will solve your problem.
https://codepen.io/bearnithi/pen/KEPXrX
const textArea = document.getElementById('code');
const btn = document.getElementById('checkcode');
const result = document.getElementById('result');
let originalHTML = `<html><head>
<title>Hello </title>
</head><body>
<p class="hello"></p>
</body>
</html>`
btn.addEventListener('click', checkCode);
function checkCode() {
let newHTMLCode = textArea.value.replace(/\s/g,"");
let oldHTMLCode = originalHTML.replace(/\s/g,"");
if(newHTMLCode === oldHTMLCode) {
console.log(true);
result.innerHTML = 'TRUE';
} else {
console.log(false);
result.innerHTML = 'FALSE';
}
}
<textarea id="code">
</textarea>
</br>
<button id="checkcode">Check Code</button>
<p id="result"></p>
You can convert all of them to one uniform and compare them.
Example:
remove all space, tab (with one space)
replace all ' to "
sort attribute.
and some rule you defined
Example cheerio to get attribute:
var cheerio = require('cheerio');
var yourString = `<html><body attr2='hi' attr1='hello' style='color:white;background:purple;'></body></html>`;
var $ = cheerio.load(yourString);
var yourAttrs = $('body')[0].attribs;
var sorted = {};
Object.keys(yourAttrs).sort().forEach(function(key) {
sorted[key] = yourAttrs[key];
});
console.log(sorted);

My string reversing function appends “undefined” at the beginning

I have a short piece of HTML and JavaScript code. I wanted to write a function that reverses the input string. For example, input = hello, output = olleh.
This is what I have so far:
function go() {
var input = document.getElementById("input").innerHTML;
var output = document.getElementById("input");
var result = "";
for (var i = input.length; i >= 0; i--) {
result += input[i];
}
output.innerHTML = result;
}
onload = go;
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="question4.js"></script>
</head>
<body>
<div id="input">This text here</div>
<div id="output"></div>
</body>
</html>
Everything works fine, but the output has an undefined in front of the result. It looks like this:
undefinedereh txet sihT
How do I make the undefined go away?
Change: var i = input.length to var i = input.length-1 because the first time you loop you will be attempting to get input[i] (where i is the length of the input array).
If the array has 10 items in it, i will be 10, however the correct index for element 10 is 9.
start the loop from input.length-1

"Writing" inside a HTML page using JS and JS scope

I'm developing a program which basically just receives input from the user twice (risk carrier and sum, but that's just a placeholder to make my program less abstract), groups those two values together and then repeats the contents in a loop. See the code below.
<head>
<script type="text/javascript">
function fillArray(){
document.getElementById("danke").innerHTML = "Thanks for specifying the amount of entries.";
var numberOfEntries = parseInt(document.getElementById('input0').value);
var i = 0;
var myArrA = [];
var myArrB = [];
var x = " ";
while(i<numberOfEntries){
var neuRT = prompt("Enter a risk carrier");
myArrA.push(neuRT);
var neuRH = prompt("Enter a risk sum");
myArrB.push(neuRH);
i++;
}
for(i = 0; i<anzahlEintraege; i++){
x = myArrA[i] + " carries a risk of " + myArrB[i];
document.getElementById("test").innerHTML = x;
}
}
</script>
</head>
<body>
<h1>risk assessment</h1>
<input type="text" id="input0" />
<button type="button" onclick="fillArray()">Number of entries</button> <p id="danke"></p>
<button type="button" onclick="untilNow()">Show all entries so far</button>
<br />
<br />
<div id="test"></div>
</body>
</html>
My issues are:
1.) I want to display the array by writing into an HTML element, which I attempted in the for-loop. Pop-ups are to be avoided. How can I loop through HTML elements, such as demo1, demo2, demo3 etc.? I can't just write <p id="demo" + i></p>. What other options are there?
2.) Say I want to make use of the untilNow() function. The scope of my arrays is limited to fillArray(). Do I need to "return" the arrays to the untilNow() function as parameters?
Thanks everyone!!!
The problem with your current code is that you're replacing the html by the last value in every loop. You're using = rather than +=. So, a quick fix would be to replace:
document.getElementById("test").innerHTML = x;
by:
document.getElementById("test").innerHTML += x;
An example of how you could wrap an array of strings in HTMLElements and add them to your document (note that there are many other ways/libraries to achieve the same result):
var myStrings = ["Hello", "stack", "overflow"];
// Two performance rules:
// 1. Use a fragment to prevent multiple updates to the DOM
// 2. No DOM queries in the loop
var newContent = myStrings.reduce(function(result, str) {
var li = document.createElement("li");
var txt = document.createTextNode(str);
li.appendChild(txt);
result.appendChild(li);
return result;
}, document.createDocumentFragment());
// Actually add the new content
document.querySelector("ul").appendChild(newContent);
<ul class="js-list"></ul>

Make HTML text bold

I wrote this function which takes in a word as input and puts it in a <b> tag so that it would be bold when rendered in HTML. But when it actually does get rendered, the word is not bold, but only has the <b> tag arround it.
Here is the function:
function delimiter(input, value) {
return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3');
}
On providing the value and input, e.g. "message" and "This is a test message":
The output is: This is a test <b>message</b>
The desired output is: This is a test message
Even replacing the value with value.bold(), returns the same thing.
EDIT
This is the HTML together with the JS that I m working on:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var children = document.body.childNodes;
for(var len = children.length, child=0; child<len; child++){
if (children[child].nodeType === 3){ // textnode
var highLight = new Array('abcd', 'edge', 'rss feeds');
var contents = children[child].nodeValue;
var output = contents;
for(var i =0;i<highLight.length;i++){
output = delimiter(output, highLight[i]);
}
children[child].nodeValue= output;
}
}
}
function delimiter(input, value) {
return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3'));
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="knorex"/>
These words are highlighted: abcd, edge, rss feeds while these words are not: knewedge, abcdefgh, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
I'm basically getting the result of the delimiter function and changing the nodeValue of a child node.
Is it possible there is something wrong with the way I'm taking back what the function is returning to me?
This is what I do:
children[child].nodeValue = output;
You need to have the markup processed as HTML, instead of being just set to replace existing content in a text node. For this, replace the statement
children[child].nodeValue= output;
by the following:
var newNode = document.createElement('span');
newNode.innerHTML = output;
document.body.replaceChild(newNode, children[child]);

How do I write a variable a certain amount of times?

var x=5
var char="Hi!
Is there any way to make JS write char x amount of times inside of an html element?
<span>Hyper guy wants to tell you
<script>
var x=5;
var char="Hi!;
document.write(char) and repeat x times;
</script>
</span>
The problem with using document.write is that it erases the whole page, so how would I insert it in context?
Use a loop that loops 5 times, each time adding 'Hi!' onto the end.
var x = 5;
var char = '';
while (x--) {
char += 'Hi!';
}
// write once
document.write(char);
Or, you can just write 5 times:
var x = 5;
var char = 'Hi!';
while (x--) {
document.write(char);
}
Up to you which you choose, though I'd prefer the first (the less you mess with the document, the better).
try this:
<span>Hyper guy wants to tell you
<script type="text/javascript">
var x=5;
var c="Hi!"; //close the quotes.
for (;x>=0;--x)
document.write(c);
</script>
</span>
document.write(..) doesnt erase the content of the entire page, if it is used in a proper way.
Really? I'm not sure where you got the idea that it erases the page first.
When I execute the following in FF3, after adding the missing closing quote following Hi!:
<html>
<head></head>
<body>
<span>
Hyper guy wants to tell you
<script type="text/javascript">
var x=5;
var chars="Hi! ";
var i;
for (i = 0; i < x; i++) document.write(chars);
</script>
</span>
</body>
</html>
I get:
Hyper guy wants to tell you Hi! Hi! Hi! Hi! Hi!
Create a HTML element in the page where you want to insert text
Use document.getElementById to get the element and append the text to element using .innerHTML .text property to it
http://www.tizag.com/javascriptT/javascript-innerHTML.php
example:
//add this empty span in the HTML page
<span id="newText"></span>
<script type="text/javascript">
var x=5, count;
var char='Hi!', resultString = '';
for(count=0;count<x;count++)
{
resultString = resultString + char;
}
document.getElementById('newText').innerHTML = resultString;
</script>

Categories