I am trying to print 6 random numbers after clicking a button. Then every time I click the button again, random numbers should start from new line however I do not know how. I tried everything and nothing works. I appreciate any help.
function fname() {
for(i=1; i<=6; i++) {
number = number + Math.floor(Math.random() * 47 + 1) + "-";
var print = number + " GOOD LUCK!";
}
document.getElementById("total").value = print;
}
<!DOCTYPE html>
<html>
<head>
<title>Let's ROLL!</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
input, button {display: block;}
</style>
<script>
var number = "";
function fname() {
for(i=1; i<=6; i++) {
number = number + Math.floor(Math.random() * 47 + 1) + "-";
var print = number + " GOOD LUCK!";
}
document.getElementById("total").value = print;
}
</script>
</head>
<body>
<div>
<button onclick="fname()">ROLL!</button>
<textarea id="total" rows="12" cols="50" readonly></textarea>
</div>
</body>
</html>
Not 100% clear on where you wanted the breaks, but in a text area, a line break is \n. If this was in an HTML element, you would use <br />.
var number = "";
function fname() {
for (i = 1; i <= 6; i++) {
number = number + Math.floor(Math.random() * 47 + 1) + "-";
}
number = number + "\n";
var print = number + "GOOD LUCK!";
document.getElementById("total").value = print;
}
input,
button {
display: block;
}
<div>
<button onclick="fname()">ROLL!</button>
<textarea id="total" rows="12" cols="50" readonly></textarea>
</div>
Add "\n".
I am assuming you want to concatenate the new text in the text area, so you should use += instead of =:
document.getElementById("total").value += print + "\n";
You can use arrays and .join() the numbers and lines together by their appropriate delimiters. This only inserts the characters between the elements. \n in a string renders a new line.
var button = document.getElementById('roll');
var total = document.getElementById('total');
var rolls = [];
button.onclick = function() {
var roll = [];
for(var i=0; i<6; ++i) roll.push(Math.floor(Math.random() * 47 + 1));
rolls.push(roll.join('-'));
total.value = rolls.join('\n') + "\nGOOD LUCK!";
}
<button id="roll">ROLL!</button><br>
<textarea id="total" rows="12" cols="50" readonly></textarea>
Related
var num1 = Math.floor(Math.random()*9 + 1);
var num2 = Math.floor(Math.random()*9 + 1);
var num_multiple = num1 * num2;
var form = document.querySelector('form');
var input = form.querySelector('input');
var button = form.querySelector('button');
var quesiton = document.querySelector('.p1');
var result = document.querySelector('.p2');
quesiton.textContent = String(num1) + " multiplication " + String(num2) + " = ? ";
form.addEventListener("submit",function(e){
e.preventDefault;
if(num_multiple === Number(input.value)){
num1 = Math.floor(Math.random()*9 + 1);
num2 = Math.floor(Math.random()*9 + 1);
num_multiple = num1 * num2;
quesiton.textContent = String(num1) + " multiplication " + String(num2) + " = ? ";
input.value = "";
result.textContent = "good";
input.focus();
}
else{
input.value = "";
result.textContent = "bad";
input.focus();
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div><p class="p1"></p></div>
<form>
<input type="text">
<button>submit</button>
</form>
<div><p class="p2"></p></div>
<script src="multiple.js"></script>
</body>
</html>
I'm sorry that I can't speak English so I use a translator to translate it.
The problem is that if the num_multiple and number (input.value) values are equal, "good" comes out very quickly and disappears very quickly. Also, input.focus(); does not work.
The problem is that a new question is written in quesiton even though the num_multiple and number(input.value) values are not equal.
How should I fix the code?
You need to call e.preventDefault
i.e do e.preventDefault() instead of e.preventDefault. This is causing the page to reload (default submit behavior), hence the input.focus() not working
You forgot the parentheses at the end of e.preventDefault (to make it a function). Other than that I also updated your code to DRY it out. DRY stands for Don't Repeat Yourself. You had a few lines of duplicate code that I put into a single function setNumbers() to make it DRY. I also made the result.textContent lines into a single ternary operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
var num1, num2, num_multiple
var form = document.querySelector('form');
var input = form.querySelector('input');
var quesiton = document.querySelector('.p1');
var result = document.querySelector('.p2');
function setNumbers(){
input.value = "";
num1 = Math.floor(Math.random() * 9 + 1);
num2 = Math.floor(Math.random() * 9 + 1);
num_multiple = num1 * num2;
quesiton.textContent = String(num1) + " multiplication " + String(num2) + " = ? ";
input.focus();
}
form.addEventListener("submit", function(e) {
e.preventDefault();
var correctAnswer = num_multiple === Number(input.value);
result.textContent = correctAnswer ? "good" : "bad";
if(correctAnswer){
setNumbers()
}
})
setNumbers()
<div>
<p class="p1"></p>
</div>
<form>
<input type="text">
<button>submit</button>
</form>
<div>
<p class="p2"></p>
</div>
<script src="multiple.js"></script>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
full:
https://onlinegdb.com/HJN6CGLTD
I need help in here : want a code that check input1 and see if its already in array or not if it is error if not push it in array.
function AddPoints()
{
var item = document.getElementById("input1").value;
if (points.includes(item) === false) points.push(parseInt( item )); // duplicate check
else document.getElementById("demo2").innerHTML = "The number Exist" ; // duplicate error
displayPoints();
}
if i understand your question you can try this code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<label>input</label>
<input id="input1" type="text"/>
<input type="button" value="Add" onclick="AddPoints()"/>
<div id="demo"></div>
<div id="demo2"></div>
</body>
</html>
JS:
var i;
var points=[];
function AddPoints(){
var item = document.getElementById("input1").value;
item=parseInt(item);//only integer number
// I check if the item is a integer number
if(Number.isInteger(item)){
//when the item's value is not present in the array
if (points.includes(item,0) === false) {
points.push( item ); // new value
document.getElementById("demo2").innerHTML = "" ;
//displayPoints();
}
else {
document.getElementById("demo2").innerHTML = "The number Exist" ; // duplicate error
//displayPoints();
}
}
else{
document.getElementById("demo2").innerHTML = "The number error" ; // It is not a number
}
displayPoints();
}
function displayPoints(){
var i;
text = "<table border=1>";
for (i = 0; i < points.length; i++) {
text += "<tr>";
text += "<td>" + (i+1) + "</td>";
text += "<td>" + points[i] + "</td>";
text += "</tr>"
}
text += "<table>";
document.getElementById("demo").innerHTML = text;
}
this is a test with the code
var i;
var points=[];
function AddPoints(){
var item = document.getElementById("input1").value;
item=parseInt(item);//only integer number
if(Number.isInteger(item)){
if (points.includes(item,0) === false) {
points.push( item );// new value
document.getElementById("demo2").innerHTML = "" ;
//displayPoints();
}
else {
document.getElementById("demo2").innerHTML = "The number Exist" ; // duplicate error
//displayPoints();
}
}
else{
document.getElementById("demo2").innerHTML = "The number error" ; // It is not a number
}
displayPoints();
}
function displayPoints(){
var i;
text = "<table border=1>";
for (i = 0; i < points.length; i++) {
text += "<tr>";
text += "<td>" + (i+1) + "</td>";
text += "<td>" + points[i] + "</td>";
text += "</tr>"
}
text += "<table>";
document.getElementById("demo").innerHTML = text;
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<script>
</script>
<body>
<label>input</label>
<input id="input1" type="text"/>
<input type="button" value="Add" onclick="AddPoints()"/>
<div id="demo"></div>
<div id="demo2"></div>
</body>
</html>
I have a code that will copy the file names and add them to the textarea. Everything works but when you add more files, the first ones are deleted. How to fix it?
updateList = function() {
var input = document.getElementById('file');
var output = document.getElementById('fileList');
output.innerHTML = '';
for (var i = 0; i < input.files.length; ++i) {
output.innerHTML += '\n' + input.files.item(i).name + '';
}
output.innerHTML += ' \n';
}
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Display file name in page after selecting file in file input</title>
</head>
<form>
<input type="file" name="file" id="file" multiple
onchange="javascript:updateList()" />
<br/>Selected files:
<textarea id="fileList"></textarea>
<script src="js/index.js"></script>
</body>
</html>
FIDDLE: https://jsfiddle.net/yhw8zfue/
You are setting your textarea value to empty string.
You can fix by removing the line:
output.innerHTML = '';
When you add more files the function will run again and updste your filelist. but in your code you reset the list of files here:
output.innerHTML = '';
so instead you want to have whats currently in there. replace it with that:
updateList = function() {
var input = document.getElementById('file');
var output = document.getElementById('fileList');
output.innerHTML = output.value;
for (var i = 0; i < input.files.length; ++i) {
output.innerHTML += '\n' + input.files.item(i).name + '';
}
output.innerHTML += ' \n';
}
I can't figure out why this code won't display the user entered information. I need to have user enter information from the html form, add this info to the arrays, and then display the info (actually, need to do more than this, but can't get past this point). I need the entered information to display on the page. Thanks
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Homework 10</title>
<script type="text/javascript">
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Variables from user input
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
//Variable for display
var display = document.getElementById("display");
//Function to add user info to arrays
function insert() {
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "LastName: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
</script>
</head>
<body bgcolor="Cornsilk">
<h2>Average Student Scores</h2>
<form>
<fieldset>
<legend><strong>Enter First, Last Name and Test Score:</strong></legend><br />
<input type="text" id="firstName" placeholder="First name"/><p />
<input type="text" id="lastName" placeholder="Last name"/><p />
<input type="number" id="testScore" placeholder="Test Score"/><p />
<input type="button" value="Save/Show Average" onclick="insert()"/><p />
</fieldset><p />
</form>
<div id="display"></div>
</body>
</html>
I tried to run the code. I got an error like
test.html:23 Uncaught ReferenceError: fName is not defined
You can solve this by moving the variable declaration inside the function.
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Function to add user info to arrays
function insert() {
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
var display = document.getElementById("display");
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "LastName: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
The reason for this is the element is no there when the initial declaration is happening.
Move the script below the body
The main issue is that the Javascript is loaded before the HTML. As a result, when the Javascript attempts to find the element with the element "firstName", it fails to find it because it hasn't been loaded yet.
To fix this, you should move the script tag below the body tag so that the HTML is loaded before it is accessed by the Javascript.
As an added bonus, it improves page load time as the browser doesn't have to wait for the JavaScript to load before rendering the HTML
Example Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Homework 10</title>
</head>
<body bgcolor="Cornsilk">
<h2>Average Student Scores</h2>
<form>
<fieldset>
<legend><strong>Enter First, Last Name and Test Score:</strong></legend><br />
<input type="text" id="firstName" placeholder="First name"/><p />
<input type="text" id="lastName" placeholder="Last name"/><p />
<input type="number" id="testScore" placeholder="Test Score"/><p />
<input type="button" value="Save/Show Average" onclick="insert()"/><p />
</fieldset><p />
</form>
<div id="display"></div>
</body>
<script type="text/javascript">
//Variables for arrays
var fName = [];
var lName = [];
var tScore = [];
//Variables from user input
var fNameInput = document.getElementById("firstName");
var lNameInput = document.getElementById("lastName");
var tScoreInput = document.getElementById("testScore");
//Variable for display
var display = document.getElementById("display");
//Function to add user info to arrays
function insert() {
fName.push(fNameInput.value);
lName.push(lNameInput.value);
tScore.push(tScoreInput.value);
clearAndShow();
}
//Function to display info entered from array
function clearAndShow() {
fNameInput.value = "";
lNameInput.value = "";
tScoreInput.value = "";
display.innerHTML = "";
display.innerHTML += "First Name: " + fName.join(", ") + "<br/>";
display.innerHTML += "Last Name: " + lName.join(", ") + "<br/>";
display.innerHTML += "Test Score: " + tScore.join(", ") + "<br/>";
}
</script>
</html>
This is my whole html page
<html>
<head>
<title> text conversion</title>
<script type="text/javascript">
function testResults(form)
{
var str = form.stringn.value;
str.split(" ");
document.write("testing1");
var length = str.length;
var newn = "";
for(var i = 0; i<length; i++)
{
if(str[i].charAt(str[i].length - 1) != ".")
{
str[i] = str[i] + ".";
}
str[i] = str[i] + " ";
str[i].charAt(0) = str[i].charAt(0).toUpperCase();
newn = newn + str[i];
}
document.write(newn);
document.write("testing");
}
</script>
</head>
<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>
</html>
The html is being displayed correctly, but the button does not produce any action. I even tried document.write("testing") below the loop in the javascript, which had no effect, which makes me think the function is not being called at all. The idea of the function is to format the input string to capitalise the first letter of each word, and put a period after each word.
This is my first time trying to use javascript, so possibly I'm doing something wrong that should be obvious?
final solution:
<html>
<head>
<title> text conversion</title>
<script type="text/javascript">
function testResults(form)
{
var str = form.stringn.value;
var strn = str.split(" ");
var length = strn.length;
var newn = "";
for(var i = 0; i<length; i++)
{
if(strn[i].charAt(strn[i].length - 1) != ".")
{
strn[i] = strn[i] + ".";
}
strn[i] = strn[i].charAt(0).toUpperCase() + strn[i].slice(1);
strn[i] = strn[i] + " ";
newn = newn + strn[i];
}
document.write(newn);
}
</script>
</head>
<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>
</html>
This should work. Also, echoing The comments before about using new as a variable.
<html>
<head>
<title> text conversion</title>
<script language="JavaScript">
function testResults(form)
{
var str = form.stringn.value;
var newString = "";
var strList = str.split(" ");
for(var i = 0; i < strList.length; i++){
newWord = strList[i].charAt(0).toUpperCase() + strList[i].slice(1) + ".";
newString += newWord + " ";
}
document.write(newString);
}
</script>
</head>
<body>
<form name="stringform" action="" method="get">
Text: <input type="text" name="stringn"><br>
<input type="button" name="Convert" Value="convert" onClick="testResults(this.form)">
</form>
</body>
</html>
Set <script type="text/javascript"> in your <head>!