my javascript code is not linking to the dom [duplicate] - javascript

This question already has answers here:
What is innerHTML on input elements?
(10 answers)
Closed 2 years ago.
I was challenged to create a function that recognizes a prime number and that was working great on the console until I linked my const number to the input and my function to the button.
const btn = document.querySelector('.btn1')
if (btn) {
btn.addEventListener('click', isitPrime)
}
function isitPrime() {
const number = document.querySelector('.input1').innerHTML
const answer = document.querySelector('.answer')
let isPrime = true
for (let i = 2; i < number; i++) {
if (number % i === 0) {
isPrime = false
answer.innerHTML = (`${number} is not prime
${number} can be divided by ${i}`)
}
if (isPrime) {
answer.innerHTML = (`${number} is prime`)
}
}
}
<input type="text" class="input1">
<button class="btn1">click here</button> <br/><br/>
<div class="answer"></div>
How to solve this problem?

In order to get the value of an input you have to use the value property instead of the innerHtml one, like this :
const btn = document.querySelector('.btn1')
if(btn){
btn.addEventListener('click', isitPrime)
}
function isitPrime(){
// here we get 'value' property instead of 'innerHtml' property
const number = document.querySelector('.input1').value
const answer = document.querySelector('.answer')
let isPrime = true
for(let i = 2; i < number; i++){
if(number % i === 0){
isPrime = false
answer.innerHTML = (`${number} is not prime
${number} can be divided by ${i}`)
}
if(isPrime){
answer.innerHTML = (`${number} is prime`)
}
}
}
<input type="text" class="input1">
<button class="btn1">click here</button> <br/><br/>
<div class="answer"></div>

document.querySelector('.input1').innerHTML
This is wrong
You should use
document.querySelector('.input1').value

Related

simple javascript number game [closed]

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 5 months ago.
Improve this question
substract 7 every time (starting number is 100), the first answer will be 93, i dont want user to move on until he gets the first answer right
let answerInput = document.getElementById("inpu");
let checkButton = document.getElementById("send");
let answers = [];
for(let i = 100; i>2;){
i -= 7;
answers.push(i);// [93, 86,...]
}
checkButton.onclick = function(){
//my struggle here
if(isNaN(answerInput.value) === true){
answerInput.value = "";
answerInput.placeholder = "only numbers are allowed";
}
}
There is no need to store the numbers in an array, seen as the next number is always 7 from the last, just keep a counter for the number. And then just compare this to the input - 7;
eg.
const span = document.querySelector('span');
const input = document.querySelector('input');
const button = document.querySelector('button');
let number = 100;
const showNum = () => span.innerText = number;
showNum();
button.addEventListener('click', () => {
const want = number - 7;
if (Number(input.value) === want) {
if (want == 2) {
alert("Well done you..");
} else {
number -= 7;
showNum();
}
}
});
Subtract 7 from <span></span> = <input type="number" value="100"/><button>Try</button>
Solution:
let answerInput = document.getElementById("inpu");
let checkButton = document.getElementById("send");
let answers = [];
for (let i = 100; i > 2; ) {
i -= 7;
answers.push(i); // [93, 86,...]
}
checkButton.onclick = function () {
if (isNaN(answerInput.value) === true) {
answer.value = "";
answer.placeholder = "only numbers are allowed";
}
// check if answer correct, `!=` compare with type coercion
else if (answerInput.value != answers[0]) {
answer.placeholder = "try again"
}
else {
answers.shift(); // remove first array element
answer.placeholder = "correct!"
}
};
<!DOCTYPE html>
<html>
<head></head>
<body>
<!--
You can use type="number" to auto-avoid letters in field:
<input id=inpu type="number" />
-->
<input id=inpu />
<input disabled id=answer />
<button id=send>Send</button>
</body>
</html>

Checking a string for numbers less than a and greater than b [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 2 years ago.
Again, I have no idea what is going wrong here. I tried debugging but it just returns false no matter what I do. It is supposed to check for a number in the input string, then check if that number is greater than the input variable A and less than the input variable B.
function ageCheck(string, a, b) {
const found = string.match(/\d{2,3}/gm)
let containsNumber = false
for (let i = 0; i < found.length; i++) {
const number = parseInt(found[i])
if (number > a && number < b) {
let containsNumber = true
}
}
return containsNumber
}
Just as snow has said you are declaring the "containsNumber" variable twice and this won't work with let, if you wan't to declare it again you can use var instead but it's not a good idea!
function ageCheck(string, a, b) {
const found = string.match(/\d{2,3}/gm)
let containsNumber = false
for (let i = 0; i < found.length; i++) {
const number = parseInt(found[i])
if (number > a && number < b) {
containsNumber = true //remove let keyword
}
}
return containsNumber
}

Debug this and help to find the solve this [duplicate]

This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 2 years ago.
function stringGen(num) {
var result = "";
var alpha =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
var alpha1 = alpha.length;
for (var i = 0; i < num; i++) {
result += alpha.charAt(Math.floor(Math.random() * alpha1));
}
return result;
}
var number = document.getElementById("num");
console.log(stringGen(number));
<html>
<body>
<div>
Enter the length of character:
<input type="text" id="num" />
<button onclick="stringGen(5)">submit</button>
<p id="result"></p>
</div>
<script type="text/javascript" src="app/index.js"></script>
</body>
</html>
Please find the error. I'm not getting the answer to this. I want to display the random text with the length from the value given in the text field in HTML.
I have update your code to fix not showing random text .
At first i get input data by var num = +document.getElementById("num").value; I use + for convert into integer. you code is not showing becouse you do not write any code to show. use document.getElementById("result").innerHTML =result to show in div.
function stringGen(num) {
var result = "";
var alpha =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
var alpha1 = alpha.length;
for (var i = 0; i < num; i++) {
result += alpha.charAt(Math.floor(Math.random() * alpha1));
}
return result;
}
function showResult(){
var num = +document.getElementById("num").value;
document.getElementById("result").innerHTML =stringGen(num);
}
<div>
Enter the length of character:
<input type="text" id="num" />
<button onclick="showResult()">submit</button>
<p id="result"></p>
</div>

How can I add 5 numbers on a empty array using 1 textbox?

I want to enter five numbers into the array using one text box. And find the max number print it when I click the result button. I want to enter a number one by one when I clicked the add button it automatically add one by one to the array. HTML with JavaScript
var input = document.getElementById('input').value;
function Add(numbers) {
numbers = [];
for(int x = 0; x < 5; x++) {
var numbers = input[x];
}
return numbers;
}
function findMax(arr) {
var max = arr[0];
for(var i = 0; i < arr.length; i ++) {
if(arr[i] > max) max = arr[i];
}
return max;
}
function Result() {
document.write(document.getElementById('demo').innerHTML = findMax(arr))
}
<p id = "demo">Print here the result</p>
<input type = "text"; id = "input">
<button onclick = "Add()">Add</button>
<button onclick = "Result()">Result</button>
To get all the 5 elements in an array using a single textbox, if they are seperated by single space do this:
var arr = input.split(' ');
This will create an array 'arr' with the numbers in it!
Actually there are many errors, that needs to be fixed, in the code you wrote:
You are declaring the numbersarray twice, inside your add function, while you should be declaring it only once globally outside of it.
You don't need a loop to add the input value into the array, just use .push().
You don't need to return the numbers array after adding an element.
Don't use document.write() to show the result, just use document.getElementById('demo').innerHTML = findMax(numbers).
Make sure to pass the right numbers array to your findMax()function, instead of arr in findMax(arr).
Demo:
This is a demo with these errors corrected.
var input = document.getElementById('input');
var numbers = [];
function Add() {
if (numbers.length < 5) {
numbers.push(+input.value);
input.value = "";
}
}
function findMax(arr) {
var max = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}
function Result() {
console.log(numbers);
document.getElementById('demo').innerHTML = findMax(numbers);
}
<p id="demo">Print here the result</p>
<input type="text" ; id="input">
<button onclick="Add()">Add</button>
<button onclick="Result()">Result</button>
You can try this code bellow :
<body>
<p id = "demo">Print here the result</p>
<input type = "text"; id = "input">
<button onclick = "Add()">Add</button>
<button onclick = "Result()">Result</button>
<script>
var numbers=[];
function Add() {
var input = document.getElementById('input').value;
if(input != ""){
numbers.push(parseFloat(input));
}
document.getElementById('input').value="";
console.log(numbers);
}
function Result() {
console.log(numbers);
document.getElementById('demo').innerHTML = Math.max.apply(null, numbers);;
}
</script>
</body>

User inputs the number of unique numbers they want to generate in javascript [duplicate]

This question already has answers here:
Random number generator without dupes in Javascript?
(7 answers)
array of random numbers [duplicate]
(1 answer)
Closed 8 years ago.
I am looking to generate x number of unique numbers between 1-10 ( whatever the user types in a input box) . So far I can generate x number of the same unique number. It needs to have an input.
function addFields(){
var number = document.getElementById("member").value;
var container = document.getElementById("container");
var arr = Math.floor((Math.random() * 10) + 1);
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
container.appendChild(document.createTextNode(" " + (arr)));
var input = document.createElement("input");
input.type = "number";
container.appendChild(document.createElement("br"));
}
}
https://jsfiddle.net/andrew1814/by62764z/1/
Thanks for your help!
You want to generate everytime a random number so you can move arr variable inside the iterator:
function addFields() {
var number = document.getElementById("member").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++) {
//move arr here
var arr = Math.floor((Math.random() * 10) + 1);
container.appendChild(document.createTextNode(" " + (arr)));
var input = document.createElement("input");
input.type = "number";
container.appendChild(document.createElement("br"));
}
}
<input type="text" id="member" name="member" value="">Number of members: (max. 10)
<br />
See Numbers
<div id="container" /></div>
Here is a function that will generate an array of x unique numbers 1-10:
function generateUnique (x) {
var numbers = [];
while(x > 0) {
var r = Math.floor((Math.random() * 10) + 1);
if(numbers.indexOf(r) === -1) {
numbers.push(r);
x--;
}
}
return numbers;
}
alert(generateUnique(5));

Categories

Resources