I need to write a code in a way only the numbers 1 - 9 are able to be input into a text field.
Whatever the number in that is input into the text field, will output of the timetables from 1-9 for that number.
For example, if the number "1" was input: 1 x 1 = 1 to 1 x 9 = 9 will be listed.
I can't figure out how to limit the input numbers to only 1,2,3,4,5,6,7,8 and 9. Here's the code I have so far:
<html>
<head>
<script>
function table(){
var integerInput = document.getElementById("integer");
var integer = Number(integerInput.value);
var displayField = document.getElementById("display");
//Reset the innerHTML when a new integer is inserted
displayField.innerHTML = "";
//Loop from 1 -> 9
for(let i = 1; i <= 9; i++) {
//Append the current times table to the HTML
displayField.innerHTML += `${integer} x ${i} = ${integer*i}<br>`
}
}
</script>
</head>
<body>
Enter an integer from 1 to 9:
<input id="integer" type="text">
<button onclick="table()" onclick="table2()">Generate times table</button>
<p id="display"></p>
</body>
</html>
Just make sure that your integer variable is an integer between 1 and 9:
function table() {
var integerInput = document.getElementById("integer");
var integer = Number(integerInput.value);
if (!Number.isInteger(integer) || integer < 1 || integer > 9) {
throw new Error('Number is not an integer between 1 and 9');
}
var displayField = document.getElementById("display");
//Reset the innerHTML when a new integer is inserted
displayField.innerHTML = "";
//Loop from 1 -> 9
for (let i = 1; i <= 9; i++) {
//Append the current times table to the HTML
displayField.innerHTML += `${integer} x ${i} = ${integer*i}<br>`
}
}
Enter an integer from 1 to 9:
<input id="integer" type="text">
<button onclick="table()" onclick="table2()">Generate times table</button>
<p id="display"></p>
Another option is to use a form with a pattern of [1-9] (though unfortunately, you can't combine a pattern with an input type="number"):
document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
var integerInput = document.getElementById("integer");
var integer = Number(integerInput.value);
if (!Number.isInteger(integer) || integer < 1 || integer > 9) {
throw new Error('Number is not an integer between 1 and 9');
}
var displayField = document.getElementById("display");
//Reset the innerHTML when a new integer is inserted
displayField.innerHTML = "";
//Loop from 1 -> 9
for (let i = 1; i <= 9; i++) {
//Append the current times table to the HTML
displayField.innerHTML += `${integer} x ${i} = ${integer*i}<br>`
}
});
Enter an integer from 1 to 9:
<form>
<input id="integer" pattern="[1-9]">
<button>Generate times table</button>
<p id="display"></p>
</form>
<html>
<head>
<script>
function table(){
var integerInput = document.getElementById("integer");
var integer = Number(integerInput.value);
var displayField = document.getElementById("display");
//Reset the innerHTML when a new integer is inserted
displayField.innerHTML = "";
//Loop from 1 -> 9
for(let i = 1; i <= 9; i++) {
//Append the current times table to the HTML
displayField.innerHTML += `${integer} x ${i} = ${integer*i}<br>`
}
}
function numbersOnly(input){
var regex = /[^1-9]/;
input.value = input.value.replace(regex, "");
}
</script>
</head>
<body>
Enter an integer from 1 to 9:
<input id="integer" onkeyup="numbersOnly(this)" maxlength="1">
<button onclick="table()" onclick="table2()">Generate times table</button>
<p id="display"></p>
</body>
</html>
The main changes I made are:
function numbersOnly(input){
var regex = /[^1-9]/;
input.value = input.value.replace(regex, "");
}
and
<input id="integer" onkeyup="numbersOnly(this)" maxlength="1">
Edit
<html>
<head>
<script>
function table(){
var integerInput = document.getElementById("integer");
var integer = Number(integerInput.value);
display_iterator(integer, "display")
display_iterator(integer, "display2")
}
function display_iterator(integer, display_id){
var displayField = document.getElementById(display_id);
//Reset the innerHTML when a new integer is inserted
displayField.innerHTML = "";
//Loop from 1 -> 9
for(let i = 1; i <= 9; i++) {
//Append the current times table to the HTML
displayField.innerHTML += `${integer} x ${i} = ${integer*i}<br>`
}
}
function numbersOnly(input){
var regex = /[^1-9]/;
input.value = input.value.replace(regex, "");
}
</script>
</head>
<body>
Enter an integer from 1 to 9:
<input id="integer" onkeyup="numbersOnly(this)" maxlength="1">
<button onclick="table()">Generate times table</button>
<table>
<tr>
<td>
<p id="display"></p>
</td>
<td>
<p id="display2"></p>
</td>
</tr>
</table>
</body>
</html>
Hope this helps :)
Related
I was working on a small project of generating a random number but there seems to be a problem.
The Generator works fine for single digit user input but not for double-digit.
For example,
if a user inputs 12 then the generator will generator will generate a password of 15 digits.
You can see the code on GitHub:
GitHub
JS CODE:
var results = document.getElementById("results");
var num;
var input;
var button = document.getElementById("gen");
var numb = "";
function getvalue(){
input = document.getElementById("user").value;
return input;
}
function randomNumber(upper){
return Math.floor(Math.random()*upper) + 1;
}
var nums = [];
button.addEventListener('click' , function() {
if(!getvalue() || getvalue() == 0){
results.innerHTML="<p>Your Have not entered any Value or Length<p>";
}
else{
var counter = 0;
while(counter<getvalue()){
var num = randomNumber(getvalue());
nums[counter] = num;
counter += 1;
}
numb = nums.join('');
results.innerHTML="<p>Your Password is :<p>" + numb;
numb = "";
nums = [];
}
});
Your randomNumber function generates random numbers between 1 and its upper parameter, which currently comes from the user input (randomNumber(getvalue());) for some reason. So, if the user input is 10 or more, the random number generated can be 10 or more, resulting in a password string that has '10' in it where there should only be one number.
Generate random numbers between 0 and 9 instead:
var results = document.getElementById("results");
var button = document.getElementById("gen");
function getvalue() {
return document.getElementById("user").value;
}
function randomNumber(upper) {
return Math.floor(Math.random() * 10);
}
button.addEventListener('click', function() {
var nums = [];
const value = getvalue();
if (!value || value == 0) {
results.innerHTML = "<p>Your Have not entered any Value or Length<p>";
return;
}
var counter = 0;
while (counter < value) {
var num = randomNumber();
nums[counter] = num;
counter += 1;
}
const numb = nums.join('');
results.innerHTML = "<p>Your Password is :<p>" + numb;
console.log(numb.length);
});
<div id="cont">
<header>
<h1>Generate Your Random Password</h1>
<p class="one">This Application generates Random Password</p>
</header>
<section id="app">
<p id="2">Enter Desired Length :)
<p>
<input type="number" id="user">
<button id="gen">Generate</button>
<div id="results">
<p></p>
</div>
</section>
</div>
I am making a website in HTML5 and Javascript which takes in some plaintext through textarea, applies a caesar cipher of 3, and sends the output to another textarea.
However, it does not produce any output.
Here is my code:
<!DOCTYPE html>
<html>
<body>
<script language="JavaScript">
var x = document.getElementById("myTextArea").value;
function c_ciph(){
for (var i = 0, len = x.length; i < len; i++) {
if (x[i] == x[i].toUpperCase()){
var a = x[i].charCodeAt(0);
var e = ((a - 65 + 3) % 26) + 97;
var c = String.fromCharCode(e);
}
else if (x[i] == x[i].toLowerCase()){
var a = x[i].charCodeAt(0);
var e = ((a - 97 + 3) % 26) + 97;
var c = String.fromCharCode(e);
}
}
document.getElementById('result').value = x;
}
</script>
<div>
<h1>Cipher and Leetspeak Converter</h1>
<p>Welcome to the cipher and leetspeak converter.</p>
</div>
<div>
<textarea id = "myTextArea" rows = "6" cols = "80">
</textarea>
<p>Convert to:</p>
</div>
<div>
<form>
<input type="radio" name="codingStyle" value="caesar_cipher" onclick="c_ciph();"> Caesar Cipher <br>
<input type="radio" name="codingStyle" value="vigenere_cipher"> Vigenere Cipher<br>
<input type="radio" name="codingStyle" value="leetspeak"> Leetspeak
</form>
</div>
<div>
<button type="button">Convert</button>
</div>
<div>
<textarea id = "result" rows = "6" cols = "80">
</textarea>
</div>
</body>
</html>
This is the site:
enter image description here
However, nothing shows up in the second text box when "Caesar Cipher"
is clicked.
I am new to Javascript and HTML, so please point out as many errors as you can.
EDIT 1: The output does appear in the 2nd text area now. However, I am having trouble changing the value of x to the ciphertext. It prints out the same value. See image here:
Instead of geek in the second textarea, there should be "iggm".
Please help.
You need to move the
var x = document.getElementById("myTextArea").value;
inside the function, So that each time function is called x is assigned new value.
function c_ciph(){
var x = document.getElementById("myTextArea").value;
for (var i = 0, len = x.length; i < len; i++) {
if (x[i] == x[i].toUpperCase()){
var a = x[i].charCodeAt(0);
var e = ((a - 65 + 3) % 26) + 97;
var c = String.fromCharCode(e);
}
else if (x[i] == x[i].toLowerCase()){
var a = x[i].charCodeAt(0);
var e = ((a - 97 + 3) % 26) + 97;
var c = String.fromCharCode(e);
}
}
document.getElementById('result').value = x;
}
Working example here
https://jsfiddle.net/vqsnmamy/2/
I have to create a html page which satisfy below requirement-
1. print 1 to 5 with another array
2. take number input from textbox then print on page whether it is Even or Odd.
I have create a page but it is not working as desired.
<HTML>
<HEAD>
</HEAD>
<BODY>
<p id="demo"></p>
<input type="number" id="myNumber">
<button onclick="oddOrEven()">Try it</button>
<input type="text" name="result" id="result" readonly="true"/>
<SCRIPT>
var numbers = [1,2,3,4,5];
var myObjects = ["One","Two","Three","Four","Five"];
var text = "";
var myObjectsList =""
var i;
for (i = 0; i < numbers.length; i++) {
text += numbers[i] + " : " + myObjects[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
function oddOrEven() {
var value = document.getElementById("myNumber").value;
var res = if((value % 2) == 0) {"Even"} else {"Odd"}*/
//if(value % 2 == 0) document.write("Even")
//document.write(value);
//document.getElementById("demo").innerHTML = res;
readonly.value=res;
}
//document.write("Hello World!");
</SCRIPT>
</BODY>
</HTML>
Could someone please help me with the code.
please see the updated solution
var numbers = [1,2,3,4,5];
var myObjects = ["One","Two","Three","Four","Five"];
var text = "";
var myObjectsList =""
var i;
for (i = 0; i < numbers.length; i++) {
text += numbers[i] + " : " + myObjects[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
function oddOrEven() {
var value = document.getElementById("myNumber").value;
var res = value % 2 == 0 ? "Even" : "Odd";
document.getElementById("result").value=res;
}
//document.write("Hello World!");
<p id="demo"></p>
<input type="number" id="myNumber">
<button onclick="oddOrEven()">Try it</button>
<input type="text" name="result" id="result" readonly/>
Updated code
var numbers = [1,2,3,4,5];
var myObjects = ["One","Two","Three","Four","Five"];
var text = "";
var myObjectsList =""
var i;
for (i = 0; i < numbers.length; i++) {
text += numbers[i] + " : " + myObjects[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
function oddOrEven() {
var value = document.getElementById("myNumber").value;
var res = value % 2 == 0 ? "Even" : "Odd";
document.getElementById("result").innerHTML=res;
}
<p id="demo"></p>
<input type="number" id="myNumber">
<button onclick="oddOrEven()">Try it</button>
<p id="result"></p>
Update2
Replace
<p id="result"></p>
with
<span id="result"></span>
There is a problem with the way you are assigning res, it should be as follows:
var res = value % 2 == 0 ? "Even" : "Odd";
Alternatively you can use an if statement if you want like so:
var res = "Odd";
if(value % 2 == 0) {
res = "Even";
}
In addition, there is also an issue with this line:
readonly.value=res;
In this case, readonly does not exist. You probably mean to do this:
document.getElementById("result").value = res;
I am new to JavaScript and am trying to program this code for my school. The ultimate goal is to make a final grade calculator where the students input their current grades and the program outputs what they need to score on the final to keep a certain percentage. This program is supposed to be for weighted classes in which the teachers weight different assignments/tests different amounts. The problem is that some teachers use more categories than others which is why there is a for loop. With the following, the user is able to input all the info but I cannot store the extra category weights and grades as a variable so I cant do the math with them. If that made any sense, I would appreciate if you knew how to store the values that are inputed within the for loops.
<html>
<head>
<script type='text/javascript'>
function addFields() {
// Number of inputs to create
var number = document.getElementById("category_weight").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++){
// create a row element to contain each pair
var row = document.createElement("div");
row.id = 'row' + i
row.appendChild(document.createTextNode("Category " + (i+1) + " weight: "));
var weight_input = document.createElement("input");
weight_input.type = "number";
weight_input.name = "weight";
row.appendChild(weight_input);
row.appendChild(document.createTextNode("Category " + (i+1) + " percentage: "));
var percentage_input = document.createElement("input");
percentage_input.type = "number";
percentage_input.name = "percentage";
row.appendChild(percentage_input);
// append inputs to row instead of container, then append each row to container
container.appendChild(row);
}
}
function weighted() {
var container = document.getElementById("container");
var rows = container.children;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var weight = row.children[0].value; // or row.querySelectorAll('[name=weight]').value;
var percentage = row.children[1].value;
console.log(weight, percentage);
}
// not important for now - will do the calculations here
// var E = "";
//
// var A = parseFloat(document.getElementById("goal_grade").value);
// var B = parseFloat(document.getElementById("exam_weight").value);
//
//
// var E = A + B;
//
// if ( E <= 0) {
// E = 0;
// }
//
//
// document.getElementById("result").innerHTML = E;
// document.getElementById("totpoints").innerHTML = B;
}
</script>
</head
<body>
<span>What final percentage in the class are you trying to reach or stay above?</span>
<input type="number" id="goal_grade" name="goal_grade" />
<br>
<br>
<span>What percent is the final exam weighted?</span>
<input type="number" id="exam_weight" name="exam_weight" />
<br>
<br>
<span>How many extra weighted categories are there?</span>
<input type="number" id="category_weight" name="category_weight" value=""> <br />
<button type="button" onclick="addFields()">Submit </button>
<div id="container"></div>
<br>
<br>
<input type="button" value="Calculate" onclick="weighted()" />
<br>
<br>
<span>You will need to get <p id="result" name="r1"> </p> points out of the ... <p id="totpoints" name="tot_points"> </p> points possible on the final"
</span>
</body>
</html>
Just use array in javascript. I have used array and your page is working fine now.
You can check it and Tell if there some problem...
<html>
<head>
<script type='text/javascript'>
var w = [];
var p = [];
var result = 0;
function addFields() {
// Number of inputs to create
var number = document.getElementById("category_weight").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++){
// create a row element to contain each pair
var row = document.createElement("div");
row.id = 'row' + i
row.appendChild(document.createTextNode("Category " + (i+1) + " weight: "));
var weight_input = document.createElement("input");
weight_input.type = "number";
weight_input.name = "weight";
row.appendChild(weight_input);
row.appendChild(document.createTextNode("Category " + (i+1) + " percentage: "));
var percentage_input = document.createElement("input");
percentage_input.type = "number";
percentage_input.name = "percentage";
row.appendChild(percentage_input);
// append inputs to row instead of container, then append each row to container
container.appendChild(row);
}
}
function weighted() {
var container = document.getElementById("container");
var rows = container.children;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
w[i] = row.children[0].value; // or row.querySelectorAll('[name=weight]').value;
p[i] = row.children[1].value;
}
for(var i =0; i < rows.length; i++){
// You can do as much calculation here with w[i] & p[i]
result += w[i]*p[i];
}
console.log(result);
// not important for now - will do the calculations here
// var E = "";
//
// var A = parseFloat(document.getElementById("goal_grade").value);
// var B = parseFloat(document.getElementById("exam_weight").value);
//
//
// var E = A + B;
//
// if ( E <= 0) {
// E = 0;
// }
//
//
// document.getElementById("result").innerHTML = E;
// document.getElementById("totpoints").innerHTML = B;
}
</script>
</head
<body>
<span>What final percentage in the class are you trying to reach or stay above?</span>
<input type="number" id="goal_grade" name="goal_grade" />
<br>
<br>
<span>What percent is the final exam weighted?</span>
<input type="number" id="exam_weight" name="exam_weight" />
<br>
<br>
<span>How many extra weighted categories are there?</span>
<input type="number" id="category_weight" name="category_weight" value=""> <br />
<button type="button" onclick="addFields()">Submit </button>
<div id="container"></div>
<br>
<br>
<input type="button" value="Calculate" onclick="weighted()" />
<br>
<br>
<span>You will need to get <p id="result" name="r1"> </p> points out of the ... <p id="totpoints" name="tot_points"> </p> points possible on the final"
</span>
</body>
</html>
I hope this will solve your problem :)
Didn't quite understand where your problem is. You can store all of your extra weighted categories inside of an array.
for example:
var categories = [];
categories.push(value);
For your issue, value can be a weighted category (weight + percentage).
Your code should be as follows:
<html>
<head>
<script type='text/javascript'>
function addFields() {
// Number of inputs to create
var number = document.getElementById("category_weight").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++){
// create a row element to contain each pair
var row = document.createElement("div");
row.id = 'row' + i
row.appendChild(document.createTextNode("Category " + (i+1) + " weight: "));
var weight_input = document.createElement("input");
weight_input.type = "number";
weight_input.name = "weight";
row.appendChild(weight_input);
row.appendChild(document.createTextNode("Category " + (i+1) + " percentage: "));
var percentage_input = document.createElement("input");
percentage_input.type = "number";
percentage_input.name = "percentage";
row.appendChild(percentage_input);
// append inputs to row instead of container, then append each row to container
container.appendChild(row);
}
}
function weighted() {
var container = document.getElementById("container");
var rows = container.children;
// The categories array initialization
var categories = [];
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var weight = row.children[0].value; // or row.querySelectorAll('[name=weight]').value;
var percentage = row.children[1].value;
// Pushing a specific category that contains weight and percentage (Defined by a JSON struction)
categories.push({
weight: weight,
percentage: percentage
});
console.log(weight, percentage);
}
// not important for now - will do the calculations here
// var E = "";
//
// var A = parseFloat(document.getElementById("goal_grade").value);
// var B = parseFloat(document.getElementById("exam_weight").value);
//
//
// var E = A + B;
//
// if ( E <= 0) {
// E = 0;
// }
//
//
// document.getElementById("result").innerHTML = E;
// document.getElementById("totpoints").innerHTML = B;
}
</script>
</head
<body>
<span>What final percentage in the class are you trying to reach or stay above?</span>
<input type="number" id="goal_grade" name="goal_grade" />
<br>
<br>
<span>What percent is the final exam weighted?</span>
<input type="number" id="exam_weight" name="exam_weight" />
<br>
<br>
<span>How many extra weighted categories are there?</span>
<input type="number" id="category_weight" name="category_weight" value=""> <br />
<button type="button" onclick="addFields()">Submit </button>
<div id="container"></div>
<br>
<br>
<input type="button" value="Calculate" onclick="weighted()" />
<br>
<br>
<span>You will need to get <p id="result" name="r1"> </p> points out of the ... <p id="totpoints" name="tot_points"> </p> points possible on the final"
</span>
</body>
</html>
Later on your calculations, your can for loop on the categories array and calculate by the categories that you've pushed into the array
This question already has answers here:
How to show a value from array that relates to the value of another array, javascript
(6 answers)
Closed 6 years ago.
I am having trouble with getting the average of the scores after I have add one in the input box. Can figure out where I am going wrong. I am able to add the input to the array but unable to calculate the average.
var names = ["Ben", "Joel", "Judy", "Anne"];
var scores = [88, 98, 77, 99];
var average;
var total = 0;
var highestScore = 0;
var name = "";
var $ = function (id) { return document.getElementById(id); };
//validate entries and add to array
var addScore = function() {
var nameInput = $("nameInput").value;
var scoreInput = $("scoresInput").value;
if ((nameInput == "" || scoreInput == "") || (scoreInput < 0 || scoreInput > 100 )){
alert("You must enter a name and a valid score");
}
else {
names[names.length] = nameInput;
scores[scores.length] = scoreInput;
}
};
//then calculate the average and highest score
var displayResults = function () {
for (var i = 0; i < scores.length; i++) {
total = total + scores[i];
if (scores[i] > highestScore) {
highestScore = scores[i];
name = names[i];
}
}
average = parseInt(total/scores.length);
$("results_header").innerHTML = ("Results");
$("results_text").innerHTML = ("\nAverage score is " + average + "<br>" + "\nHigh score = " + name + " with a score of " + highestScore);
};
//display scores table
var displayScores = function() {
$("scores_header").innerHTML = ("Scores");
$("names").innerHTML = ("Names");
$("scores").innerHTML = ("Scores");
var table = $("scores_table");
for(var i=0; i < names.length;i++) {
var row = table.insertRow(table.rows.length);
var cell = row.insertCell(0);
var cell2 = row.insertCell(1);
cell.innerHTML = names[i];
cell2.innerHTML = scores[i];
}
};
window.onload = function () {
$("add").onclick = addScore;
$("display_results").onclick = displayResults;
$("display_scores").onclick = displayScores;
};
<main>
<h1>Use a Test Score array</h1>
<label for="name">Name:</label>
<input type="text" id="nameInput"><br>
<label for="score">Score:</label>
<input type="text" id="scoresInput"><br>
<label> </label>
<input type="button" id="add" value="Add to Array" >
<input type="button" id="display_results" value="Display Results" >
<input type="button" id="display_scores" value="Display Scores" ><br>
<div id="results">
<h2 id="results_header"></h2>
<p id="results_text"></p>
</div>
<h2 id="scores_header"></h2>
<table id="scores_table">
<tr>
<th id="names" align="left"></th>
<th id="scores" align="left"></th>
</tr>
</table>
</main>
Could be because scoreInput is a string (any value from an HTML input is) and thus when you try to add the new score to the old in displayResults() it's not adding numbers, but concating a string. Try converting the input to a Number first:
var addScore = function() {
var nameInput = $("nameInput").value;
// convert score to a Number first...
var scoreInput = Number( $("scoresInput").value );
// make sure `scoreInput` is valid AND in range...
if ((nameInput == "" || scoreInput == "") || ((!scoreInput && scoreInput !== 0)|| scoreInput < 0 || scoreInput > 100 )){
alert("You must enter a name and a valid score");
}
else {
names[names.length] = nameInput;
scores[scores.length] = scoreInput;
}
};
EDIT
As #rpadovani says, you should also initialize total each time inside displayResults():
var displayResults = function () {
total = 0;
// ... (the rest of your code)
};
You did not initialize total, so when you do total = total + scores[i]; Javascript treats it as a string.
Just write var total = 0 at the start of displayResults() function