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;
Related
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 :)
i have a textbox1 which input by user and textbox2 for user to input numbers which can automatically generate textbox1 value into multiple string such as example below:
Txtbox1 = ABC12345
Txtbox2 = 3
Result will be
ABC12345-1
ABC12345-2
ABC12345-3
You can try using something like this below, but kinda hard to make it 100% as you want, since you haven't shown any HTML.
$("[id^=Txbox]").keyup(function() {
var empty = $("[id^=Txbox]").filter(function() {
return $.trim($(this).val()).length == 0
}).length == 0;
if (empty) {
var str = $("#Txbox1").val();
var number = $("#Txbox2").val();
var arr = [];
for (i = 0; i < number; i++) {
arr.push(str + "-" + i)
}
console.log(arr)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Txbox1" />
<input id="Txbox2" type="number" />
You can just use button and apply click event.
function getString() {
var finalString = [];
var t = $("#textbox1").val()
var n = $("#textbox2").val();
if (t.toString().trim() != "") {
for (i = 0; i < n; i++) {
finalString.push(t + "-" + (i + 1))
}
}
console.log(finalString)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Text : <input type="text" id="textbox1"><br><br> Number : <input type="text" id="textbox2">
<button type="button" onClick="getString()" id="textbox1">Get</button>
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
I am attempting to create an online solver for the maximum subarray problem.
https://en.wikipedia.org/wiki/Maximum_subarray_problem
I planned on taking user-input numbers from a textbox and converting them into an int array in JS, however my JS does not seem to be running at all.
Here is my HTML
<!DOCTYPE html>
<html>
<head>
<title> findMaxSum </title>
<script src="findMaxSum.js" type="text/javascript"></script>
</head>
<body>
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p> Enter numbers with spaces, i.e. "1 2 3 4 5": </p>
<input type="text" id="array"> <br>
<button id="sum">findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is: </p>
</body>
</html>
and my JS. note: the map(function(item)) part of the code is intended to break apart the string from the form into an int array.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Currently, when I type in numbers into the textbox and submit, the numbers disappear and nothing happens. Any help is greatly appreciated.
Your array variable is object. You have to split the value of <input type="text" id="array"> not the object element.
var array = document.getElementById("array");
array = array.value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Or simpler:
var array = document.getElementById("array").value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Change your code -
function findMaxSum() {
var array = document.getElementById("array").value.split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Problem is you are using button inside form, which is by default of type submit type, that is the reason why the page goes blank, it gets submitted. So either you don't use form tag or make the button as button type.
<button id="sum" type='button'>findMaxSum!</button> <!-- type attribute added -->
Below is the sample updated code, hope it helps you.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").value.split(/\s/);
var max = Math.max.apply(Math, array);
document.getElementById("answer").innerHTML = "The answer is: " + max;
}
window.onload = function() {
document.getElementById("sum").onclick = findMaxSum;
};
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p>Enter numbers with spaces, i.e. "1 2 3 4 5":</p>
<input type="text" id="array">
<br>
<button id="sum" type='button'>findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is:</p>
To achieve the solution of the problem, you need to make following changes.
Update the event binding place
window.onload = function() {
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
};
function findMaxSum() {
// remove the update binding code from here
// logic should come here
}
Resolve a JS error
document.getElementById("array").value.split(" ")
Update the html to avoid page refresh (add type)
<button id="sum" type='button'>findMaxSum!</button>
Update the logic to address the problem
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
var counter = i+1;
while (counter < array.length) {
var loopSum = array[i];
for (var j = (i+1); j <= counter; j++) {
loopSum += array[j];
if(loopSum > currentMax) {
currentMax = loopSum;
}
}
counter++;
}
}
Here is a plunker - http://plnkr.co/edit/AoPANUgKY5gbYYWUT1KJ?p=preview
var var1 = 0;
var var2 = 1;
var var3;
var num = 20;
document.write(var1 + "<br />");
document.write(var2 + "<br />");
for (var i = 3; i <= num; i++) {
var3 = var1 + var2;
var1 = var2;
var2 = var3;
document.write(var3 + "<br />");
}
Best, I'm doing a Fibonacci Series, but I want to see a message with prompt comes up, so you can fill in a number, then the returns with the Fibonacci Series. Who would be able to help me? Above I have now.
I have created demo, hope it will help you.
var i;
var fib = [0, 1];
var limit = window.prompt('Enter the limit for your series:', '');
for (i = 2; i < parseInt(limit); i++) {
fib[i] = fib[i - 2] + fib[i - 1];
}
console.log(fib);
Demo Link
function myFunction() {
var n = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = fibonacciGenerator (n);
}
var sequence = [0]; // sequence = []; if you want sequence [1] = 1;
var previousNumber = 1;
var presentNumber = 0;
var sum = 0;
function fibonacciGenerator (n) {
while (sequence.length < n) {
sum = previousNumber + presentNumber;
previousNumber = presentNumber;
presentNumber = sum;
sequence.push(sum);
}
return (sequence);
}
<!DOCTYPE html>
<html>
<body>
<h1>Fibonacci Generator </h1>
<input type="number" id="myNumber" value="0">
<p>Enter a number to generate Fibonacci array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
Using ES6 generator
function* fiboGen(len, current = 0, next = 1) {
if (len === 0) {
return current;
}
yield current;
yield* fiboGen(len - 1, next, current + next);
}
const fibo = [...fiboGen(10)];
console.log(fibo);
//[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
you need to use a prompt box to get the number:
window.prompt("sometext","defaultText");
http://www.w3schools.com/js/js_popup.asp
I hope that this is what you are looking for.
HTML:
Which sequence of the Fibonacci pattern do you want to find?
<br><br>
<input type="text" id="inputtext">
<br><br>
<input type="button" value="Find out" id="btn">
<br><br>
<b id="ID"></b>
JS:
function add(a, b) {
while (a.length < b.length) a.unshift(0);
while (a.length > b.length) b.unshift(0);
var carry = 0,
sum = [];
for (var i = a.length - 1; i >= 0; i--) {
var s = a[i] + b[i] + carry;
if (s >= 10) {
s = s - 10;
carry = 1;
} else {
carry = 0;
}
sum.unshift(s);
}
if (carry) sum.unshift(carry);
return sum;
}
function fib(n) {
var f1 = [0];
var f2 = [1];
while (n--) {
var f3 = add(f1, f2);
f1 = f2;
f2 = f3;
}
return f1.join("");
}
document.getElementById("btn").onclick = function () {
var inputnum = parseFloat(document.getElementById("inputtext").value);
document.getElementById("ID").innerHTML = fib(inputnum).toString();
};
Fiddle.
var number = prompt("Enter number ");
....... your code ....
You can do the following:
var var1 = 0;
var var2 = 1;
var var3;
var num = window.prompt("Enter the limit for your series:","");
//var num = 20;
var str = '';
str+=var1+','+var2;
for(var i=3; i <= parseInt(num);i++)
{
var3 = var1 + var2;
var1 = var2;
var2 = var3;
str+=','+var3;
}
document.write(str);
<!doctype html>
<html lang="en">
<head>
<body>
<script type="text/javascript">
var f1=0,f2=1,f3;
var i;
alert("enter a text"+n);
var n=prompt("enter the number");
document.write("the fibonacci series is "+"<br/>");
for(i=2;i<=n;i++)
{
f3=f1+f2;
f1=f2;
f2=f3;
document.write(f3+"<br/>");
}
</script>
<style>
body {background-color:#66ff66}
</style>
</head>
</body>
i came up with this solution to get the n index Fibonacci value. you can use the findFac0(); to pass the index you need to get the Fibonacci value.
function findFac(n){
if (n===1)
{
return [0, 1];
}
else
{
var s = findFac(n - 1);
s.push(s[s.length - 1] + s[s.length - 2]);
return s;
}
}
function findFac0(n){
var vv1 = findFac(n);
return vv1[n-1];
}
console.log(findFac0(10));
I've tried this: it might work:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fibonacci</title>
<style>
* {
outline: 0px;
margin: 0px;
}
input[type="number"] {
color: blue;
border: 2px solid black;
width: 99.58vw;
}
</style>
</head>
<body>
<div id="myDiv" style="color: white;background-color: blue;">Numbers Here</div>
<input type="number" id="input1" oninput="fibonacciProgram(this.value)" placeholder="Type Some Numbers Here">
<script>
function fibonacciProgram(numberCount) {
let resultElement = document.getElementById("myDiv");
resultElement.innerHTML = " ";
if (isNaN(numberCount) || numberCount <= 0) {
resultElement.innerHTML = "please enter a number";
return;
}
let firstBox = 0;
let secondBox = 1;
let swichBox;
let entries = [];
entries.push(secondBox);
while (numberCount > 1) {
swichBox = firstBox + secondBox;
entries.push(swichBox);
firstBox = secondBox;
secondBox = swichBox;
numberCount--;
}
resultElement.innerHTML = entries.join(', ');
}
</script>
</body>
</html>