Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
How do I populate some text with a paragraph using innerHTML? I need to enter a number into the textbox and then repeat some text as many times as the number entered into the textbox.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ex10.js</title>
</head>
<body>
<input type="text" id="input-type" onKeyUp="myFunction()">
<p id="sample-text">Here is some text</p>
<script>
function myFunction() {
let count = document.getElementById("input-type").value;
document.getElementById("sample-text").innerHTML = count;
if (isNaN(count)) {
document.getElementById("sample-text").innerHTML = "Error. Not a number";
}
else {
for(int i = 0; i < count; i++) {
document.getElementById("sample-text").innerHTML = "This is some text";
}
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ex10.js</title>
<script>
function myFunction() {
var count = document.getElementById("input-type").value;
if (isNaN(count)) {
document.getElementById("sample-text").innerHTML = "Error. Not a number";
}
else {
// create your empty array
var lines = "";
// loop x amount of times and add your text to the array
for (var i = 0; i < count; i++) {
lines = lines+"Atmiya\n";
}
// convert the array to a string, with each string on its own line
document.getElementById("sample-text").innerHTML = lines;
}
}
</script>
</head>
<body>
<input type="number" id="input-type" onKeyUp="myFunction()">
<p id="sample-text">Here is some text</p>
</body>
</html>
document.getElementById("sample-text").innerHTML = someVar;
This will completely overwrite the content of your html element every time you call it, which is probably your problem.
What you'll want to do instead is build your string beforehand, and then populate the element once afterwards. How about building an array, and then creating a string using join?
// create your empty array
var lines = [];
// loop x amount of times and add your text to the array
for (var i = 0; i < count; i++) {
lines.push("This is some text");
}
// convert the array to a string, with each string on its own line
document.getElementById("sample-text").innerHTML = lines.join("\n");
There are a few tricks to make it easier:
<input type="number">
<input> elements of type "number" are used to let the user enter a number. They include built-in validation to reject non-numerical entries. The browser may opt to provide stepper arrows to let the user increase and decrease the value using their mouse or by simply tapping with a fingertip.
You can also use the += operator to concatenate to an element's innerHTML property.
onchange is probably better to use than onkeyup. I'm not sure onkeyup works with a touch screen. And the number input box has little controls to change the value.
function go() {
let text = document.querySelector('#sample-text').innerHTML;
let times = document.querySelector('#times').value;
let output = document.querySelector('#output');
let ix = 0;
output.innerHTML = '';
while (ix < times) {
output.innerHTML += text;
ix++;
}
}
<input type="number" min="1" id="times" onchange="go()">
<p id="sample-text">Here is some text</p>
<p id="output"></p>
Related
DISCLAIMER: i'm legit a newbie
I have a 2nd parameter in the getInput function, I should use it for the 9 zeros that I should input. But I don't know how to loop it to become 9 zeros instead of putting it in a variable.
How do I loop and store 9 zero's into my "digit" parameter without declaring it as var zr = "000000000"
here's my code:
<html>
<head>
<title>Search</title>
<script>
//This method does the processing
function getInput(input, digit){
var str=input.substring(0,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output="A"+zrsub+""+str;
//can also be var output=input[0]+zrsub+""+str;
return output;
}
//Displays output
function showOutput(){
var input=document.getElementById("search-input").value;
var dislay=document.getElementById("search-output");
dislay.value=getInput(input);
}
</script>
</head>
<body>
<div class="wrapper">
<input type="text" id="search-input">
<input type="button" id="btn" value="ENTER" onclick="showOutput()"> <br><br>
<input type="text" id="search-output">
</div>
</body>
</html>
Sorry just a newbie in this whole programming thing. Just a little confused.
with for loop join string
function joinString(input,digit) {
var inputArr = input.split("");
// var n = 9; // the length of the ouput string;
for (var i = 0; i < digit; i++) {
inputArr.unshift(0);
if (inputArr.length === digit) {
return inputArr.join("");
}
}
}
console.log(joinString("123456"));
You can use padStart
function getInput(input, digit){
return 'A'+ input.toString().padStart(digit, '0');
}
document.getElementById('target').innerHTML = getInput(132,9)
<p id="target"></p>
IE may not support it though.
Hello there!
I've been a given a Task like so:
Request the user to enter a number
Check if the user input is not empty. Also, check value entered is a number
Write on the HTML document a triangle out of the numbers as follow:
E.g. output: (let’s say the user entered number 10)
Your input number is 10.
10
11 11
12 12 12
13 13 13 13
14 14 14 14 14
15 15 15 15 15 15
The triangle should have 6 rows.
Use Comments explaining how the program works
Follow Indentation for clarity purposes.
Here is what I've tried so far:
var input = prompt("Enter a number: ");
if (input.value == '' || input.value == input.defaultValue) {
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
}
for (input = 10; input <= 15; input++) {
var a = '';
for (var j = 10; j <= input; j++) {
var a = a + '' + input;
}
document.writeln(a + "<BR>");
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Task Write your Own Code</title>
</head>
<body>
<h1>Task Write your Own Code</h1>
</body>
</html>
First of all, my IF statement is not working properly even if I input a string or don't leave a blank input field - the alert message still pop up;
And the result of document.writeln still printed even after alert pop's up with inputted string or empty field;
Please, someone, help me to solve this task or at least tell me what I'm doing wrong?
Thanks!
Look at the documentation for window.prompt().
Remove .value. input is the value.
Also, you aren't telling your code to not run if input is "bad".
// Be in a function so that you can return
(function() {
var input = prompt("Enter a number: ");
if (!input) {
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
// Get of of the function
return;
}
for (input = 10; input <= 15; input++) {
var a = '';
for (var j = 10; j <= input; j++) {
var a = a + '' + input;
}
document.writeln(a + "<BR>");
}
}());
|| input.value == input.defaultValue makes no sense since there is no such thing as input.defaultValue and, even if there was, you only need to check for an empty string. Also, input is already the response from the user so .value isn't needed.
You need to add an else condition to your if statement because even if no number is entered, your code will continue to do the looping.
Additionally, document.write() is only ever used in rare situations where you are building a new document from scratch, dynamically. It should not be used just to update an existing page's content. Instead, prepare an empty element ahead of time and when ready, update the content of that element.
Your loop configurations were a little off as well.
See other comments inline:
// Get the user's response, converted to a number
var input = parseInt(prompt("Enter a number: "), 10);
// Get a reference to the waiting output area on the page
var output = document.getElementById("output");
// Check that a number was given
if (!isNaN(input)) {
// We have a number...
// You know you need to go 6 times
for (x = 1; x < 7; x++) {
var a = '';
// And then you need to go however many times the outer loop is on
for (var j = 1; j <= x; j++) {
a += input + ' '; // You just need to write out the current input value
}
input++; // Increase the value
// Update the output area on the page
output.innerHTML += a + "<br>";
}
} else {
// We don't have a number:
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Task Write your Own Code</title>
</head>
<body>
<h1>Task Write your Own Code</h1>
<div id="output"></div>
</body>
</html>
And, if and when you get more into String operations, you'll find that you don't even need the inner loop:
// Get the user's response, converted to a number
var input = parseInt(prompt("Enter a number: "), 10);
// Get a reference to the waiting output area on the page
var output = document.getElementById("output");
// Check that a number was given
if (!isNaN(input)) {
// We have a number...
// You know you need to go 6 times
for (x = 1; x < 7; x++) {
// Set up the string to be written and then just repeat that
// however many times the outer loop is currently on.
output.innerHTML += (input + " ").repeat(x) + "<br>";
input++; // Increase the value
}
} else {
// We don't have a number:
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Task Write your Own Code</title>
</head>
<body>
<h1>Task Write your Own Code</h1>
<div id="output"></div>
</body>
</html>
I have an assignment in school but I'm totally stuck.
My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.
My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:
<head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>
<script type="text/javascript">
var text= test.length;
for (i=0;i< test.length;i++)
function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}
</script>
</head>
<body>
<h1>Assignment 14</h1>
<form name="f1">
<input type="text" id="test" value="" />
<input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />
</form>
</body>
Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.
You have to rewrite a script.When you want to extract one by one you can use substring(); function.
How to Call : StringObject.substring (StartPoint,endPoint);
Solution:
<script type="text/javascript">
function printit(){
var test=document.getElementById("test").value;
var text= test.length;
for (i=0;i<= text;i++)
{
var res = test.substring (i, 0);
document.write(res);
document.write("<br/>");
}
}
</script>
You are on the right way. substring(start,end) in javascript gives you the consecutive part of the string letters from start index to end. You just use it in a wrong way for your case. You have to call it like this:
substring(0,i)
You need to make few changes to your code:
1) use document.getElementById('test').value in printit function call at onclick as you have to send the value of the textbox instead of innerHTML.
2) Modify the printif function-
function printit(test)
{
document.getElementById('test').value=''; /*remove existing text from textbox*/
for (i=0;i< test.length;i++) {
var res = str.substring (0, i+1);
document.getElementById("test").value += ' '+res;
}
}
In printit function empty the text box and then append each substring to the existing text to get "T Th Tho Thom.." and so on
Hope this helps.
I don't use for-loop for this (whenever possible, I prefer functional style). Instead, I write a function that returns an array of substrings:
const substrings = string =>
Array.from(string).map((_, i) => string.slice(0, i + 1))
And here's a working codepen
Output several time using substring() method can be done as below, create a function which performs this task of extracting the user inputted string on button click using forloop and substring() method.
var intp = document.querySelector("input");
var btn = document.querySelector("button");
var dv = document.querySelector("div");
btn.onclick = function() {
var b = intp.value;
for (var i = 1; i <= b.length; i++) {
var c = b.substring(0, i);
dv.innerHTML += c + "<br/>";
}
}
div{
width:400px;
background:#111;
color:yellow;
}
<input type="text">
<button>Click</button>
<br/><br/>
<div></div>
You have used a correct way for doing this, but as one of user suggest the start and end value of substring() was not correct.
Okay, so I'm trying to create a quiz application for revision purposes that asks a random question from a list of questions, takes a text input as the users answer to the question, and then compares it to the actual answer to the question. The code I have used is:
var keyList = Object.keys(htmlModule);
var ranPropName = keyList[ Math.floor(Math.random()*keyList.length) ];
var pageStart = function() {
document.getElementById("question").innerHTML = htmlModule[ranPropName][0];
document.getElementById("submit").onclick = answerValidation;
};
window.onload = pageStart;
var answerValidation = function(correctAnswer, userAnswer) {
correctAnswer = htmlModule[ranPropName][1];
userAnswer = document.getElementById("submit").value;;
if(userAnswer === correctAnswer) {
document.getElementById("rightWrong").style.backgroundColor = "green";
} else {
document.getElementById("rightWrong").style.backgroundColor = "red";
}
};
The variable htmlModule refers to the object in which the questions and their answers are stored. Each question and answer pair is stored inside an array that is the value of its property, the property simply being a key used to reference each pair e.g. htmlQ1, htmlQ2 etc.
The main problem I seem to be having is that my if statement comparing the actual answer and the user answer won't evaluate to true. I know this because the background colour of the div element rightWrong only ever turns red, even when I've definitely typed in a correct answer at which point it should turn green. My assumption is that either the text input isn't being stored for some reason, or the value of the variable ranPropName that uses Math.random() is changing due to the use of Math.method(), but I'm stuck as to how to remedy either potential problem. Thanks in advance for any replies.
Well, I started to visualize your quiz as you explained.
One thing is need to be changed is that you get userAnswer from the value of an element with Id submit which I assume most probably it's an button tag, so I write a working code sample as follow:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Title Goes Here</title>
</head>
<body>
<input type="text" id="rightWrong" />
<div id="question" />
<button id="submit">Submit</button>
</body>
<script>
var htmlModule = {
'htmlQ1': ['1+1=?', '2'],
'htmlQ2': ['2+2=?', '4']
};
var keyList = Object.keys(htmlModule);
var ranPropName = keyList[ Math.floor(Math.random()*keyList.length) ];
var pageStart = function() {
document.getElementById("question").innerHTML = htmlModule[ranPropName][0];
document.getElementById("submit").onclick = answerValidation;
};
window.onload = pageStart;
var answerValidation = function(correctAnswer, userAnswer) {
correctAnswer = htmlModule[ranPropName][1];
userAnswer = document.getElementById("rightWrong").value;
if(userAnswer === correctAnswer) {
document.getElementById("rightWrong").style.backgroundColor = "green";
} else {
document.getElementById("rightWrong").style.backgroundColor = "red";
}
};
</script>
</html>
Please share your html if you still face problems.
I'm relatively new to JavaScript and I can't seem to figure out how to output text in a textfield in HTML. I've looked at many solutions and although I'm very close (I think I am), I still can't get it to function properly.
I'm trying to sort a series of numbers by separating them with "; " and wish to show the result in the bottom text field by ascending or descending order. The action is done by pressing the button to sort them.
When trying to debug it, it seems that the variables are being assigned their values as they should, but the variable "output" just won't show up in the "Sorted Numbers" textfield. My code is incomplete as I'm just trying to test this for an ascending order before I add in the descending order.
Here is my code...
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Sorting Numbers</title>
</head>
<body>
Enter Numbers Here: <input type = "text" id = "numInput"><br><br>
Select Option: <select id = "menu">
<option value = "ascending">Ascending</option>
<option value = "descending">Descending</option>
</select><br><br>
Sorted Numbers: <input type = "text" id = "numOut"><br><br>
<button onclick = "sortNums()">Sort Numbers</button>
<script type = "text/javascript">
function sortNums() {
var choice = document.getElementById("menu");
var numbers = document.getElementById("numInput").value;
var output = document.getElementById("numOut").value;
if(choice.value = "ascending") {
arr = numbers.split('; ').sort().join('; ');
output = arr;
}
}
</script>
</body>
</html>
Because you never assigned output to it afterwards:
if(choice.value = "ascending") {
arr = numbers.split('; ').sort().join('; ');
output = arr;
document.getElementById("numOut").value = output;
}