I am making a program that has an array of numbers and then the user inputs some values in and clicks on verify. the value he enters has to be in order with the array of numbers and if it isn't the user gets an alert message sorry HOWEVER the value inside the first input bar decides from which number of the array should the comparison should start. FOR example, if the array holds numbers like {2,4,6,8,10}
and the user enters 6 in the first input bar and then he enters 8 and 10 in the next two bars, he should get the result "678" HOWEVER if he doesn't get the first number right lets say he enters 3, and since 3 isn't in the array, then it doesn't matter what he enters in the other input bars, he would get the result "Sorry". similarly, if the user types 4 in the first input bar but then then in the second bar he types 8, he should still get the result "Sorry" since the order of the array is {4,6,8} not {4,8}.. Now, i made a program but the thing is, whenever i click on the verify button, nothing happens :/.. here are my codes. and here is also the result i am getting: https://jsfiddle.net/53j19rpt/
<html>
<head>
</head>
<script type="text/javascript">
var arr = [];
var t;
var num = 2;
var x = [];
for (var x = 0; x < 4; x++) {
document.getElementById("one" + x);
}
function go() {
for (var t = 0; t < 4; k++) {
x[t] = num * (t + 1);
}
for (var k = 0; k < 4; k++) {
if (document.getElementById("one0").value >= x[k])
if (document.getElementById("one" + k).value == x[k])
document.write(document.getElementById("one" + k).value);
else
document.write("Sorry");
}
}
</script>
<body>
<input id="one0" type="text">
<input id="one1" type="text">
<input id="one2" type="text">
<input id="one3" type="text">
<input type="button" id="verifyBtn" value="verify" onclick="go()">
</body>
</html>
check this
for (var t = 0; t < 4; k++) {
x[t] = num * (t + 1);
}
Code is going for an infinite loop here. the value of t is not getting incremented in the code.
There are multiple issues here:
x first gets declared as an array (i.e. var x = [];, but then immediately after that, x gets used as an iterator for the for loop (i.e. for (var x = 0; x < 4; x++) {). Later on in the start of function go(), when assigning values to x, it attempts to access x[t], which does not work for an integer. So use a different variable in the iterator:
for (var x = 0; x < 4; x++) {
document.getElementById("one" + x);
}
In the second for loop, the variable t doesn't get incremented, which causes an infinite loop. Increment t, not k.
for (var t = 0; t < 4; t++) {
The if statements have no braces, which causes only the next line to be executed... though the two if statements in sequence will still execute the statement after the second if when both conditions evaluate to true. If you need multiple lines of code after the if expression then wrap them in curly braces.
See the example below:
var arr = [];
var t;
var num = 2;
var x = [];
for (var h = 0; h < 4; h++) {
document.getElementById("one" + x);
}
function go() {
for (var t = 0; t < 4; t++) {
x[t] = num * (t + 1);
}
for (var k = 0; k < 4; k++) {
if (document.getElementById("one0").value >= x[k]) {
if (document.getElementById("one" + k).value == x[k]) {
document.write(document.getElementById("one" + k).value);
}
else {
document.write("Sorry");
}
}//could have an else after this when one0's value is less than x[k]
}
console.log('done with function go()');
}
<input id="one0" type="text">
<input id="one1" type="text">
<input id="one2" type="text">
<input id="one3" type="text">
<input type="button" id="verifyBtn" value="verify" onclick="go()">
Related
I have loop inside loop like this:
var len = bolumlerUnique.length;
function bolumleriGonder() {
for (i = 0; i < bolumlerUnique.length; i++) {
elementBolumler = $("[bolumid=" + bolumlerUnique[i] + "]:checked");
console.log(elementBolumler);
for (j = 0; j < len; j++) {
console.log(elementBolumler[j])
}
}
}
bolumlerUnique is an array --> ["1", "2", "3", "4"]I have radio inputs and find elements with this code
$("[bolumid=" + bolumlerUnique[i] + "]:checked");
But in the second loop console.log writes undefined.
But elementBolumler is defined global variable.
Check your len variable is have a value it must work with your codes.
in the second loop console.log writes undefined.
To answer the question as (almost) presented: "why do I get undefined with $()[j]?"
Within jquery, if you attempt to get an element by index that's larger than the number of items in the jquery collection, you get undefined (not array out of bounds as it's not an array), ie:
var divs = $(".d");
console.log(divs[0])
console.log(divs[1]) // undefined
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d">d1</div>
The issue is with:
var len = bolumlerUnique.length;
for (j = 0; j < len; j++) {
When you iterate over
$("[bolumid=" + bolumlerUnique[i] + "]:checked")
it will only have as many items as are checked that match the one id. So it's highly likely that
elementBolumler.length !== len
As noted in the comments to the question, [bolumid=" + bolumlerUnique[i] + "] is a radio so it will only ever return one item.
Your logic for the inner loop index len is incorrect, but it's not clear what it should be - possibly:
elementBolumler.length
as in:
function bolumleriGonder() {
for (i = 0; i < bolumlerUnique.length; i++) {
elementBolumler = $("[bolumid=" + bolumlerUnique[i] + "]:checked");
console.log(elementBolumler);
for (j = 0; j < elementBolumler.length; j++) {
console.log(elementBolumler[j])
}
}
}
const checkboxesIWantToMessWith = [2, 4, 6]
checkboxesIWantToMessWith.forEach(id => {
const checkbox = document.querySelector(`input[bolumid="${id}"]`)
if (checkbox.checked) {
// Do my stuff
console.log(`checkbox bolumid="${id}" is checked`)
} else {
// Do other stuff
console.log(`checkbox bolumid="${id}" is NOT checked`)
}
})
<input type="checkbox" bolumid="1" checked />
<input type="checkbox" bolumid="2" checked />
<input type="checkbox" bolumid="3" checked />
<input type="checkbox" bolumid="4" />
<input type="checkbox" bolumid="5" checked />
<input type="checkbox" bolumid="6" checked />
I have a problem rendering the output of this code on textarea in html page, but it runs and shows the correct output on the console. Below is the html and javascript codes.. Thanks
<body>
<div class="input">
<div class="numb">
<form class="form-group" name="number" id="number">
<input id="textbox" type="text" name="textbox" placeholder="Enter N">
<button type="button" name="submit" id="button" onclick="final()">Get Matrix</button>
</form>
</div>
<div class="result">
<textarea id="spiral" name="spiral" placeholder="matrix"></textarea>
</div>
</div>
function createMatrix(size) {
const array = [];
for (let i = 0; i < size; i++) {
array.push(new Array(size));
}
return array;}
function spiral(input) {
const output = createMatrix(input);
let n = 1;
let a = 0;
let b = input;
let direction = 0; // 0 = right, 1 = down, 2 = left, 3 = up
let directionFlip = true;
let x = 0;
let y = 0;
while (n <= (input * input)) {
output[x][y] = n;
n++;
a++;
if (a >= b) {
a = 0;
if (direction === 0 || direction === 2 && directionFlip) {
b--;
}
directionFlip = !directionFlip;
direction = (direction + 1) % 4;
}
switch(direction) {
case 0:
x++;
break;
case 1:
y++;
break;
case 2:
x--;
break;
case 3:
y--;
break;
}
}
return output;}
A print function to define the matrix order of this form spirally
1 2 3
8 9 4
7 6 5
function print(input, paddingChar) {
const longest = (input.length * input.length).toString().length;
const padding = paddingChar.repeat(longest);
for (let y = 0; y < input.length; y++) {
let line = "";
for (let x = 0; x < input.length; x++) {
line += (padding + input[x][y]).slice(-longest) + " ";
}
console.log(line.toString());
}}
and a function to call it in the html page and return the square matrix
function final() {
input = document.getElementById("textbox").value;
let text = print(spiral(input), " ");
document.getElementById("spiral").innerHTML = text}
so if i input n from page, i get the matrix of n shown in developer console but not in the html page node
you are not returning anything from print function; here is updated fiddle to concatenate the text and return the text in matrix
https://jsfiddle.net/gowrimr/mjvn3fru/7/
`let text = ''
after console in print function add:
text = text+line.toString()+'\n'
finally do a return text
Your print function doe not return a value, therefore text is undefined. Add something like return line.toString(); at the end of your print function.
I have tried this but only from 1 to 50 or 1 to 100 prime numbers are obtained.
How should I properly find out the prime number. Which are asked by users?
<h1>enter the no.</h1><input type="text" id="limit">
<h1>enter the no.</h1><input type="text" id="limit2">
<button onclick="fun()">Submit</button>
<div id="result"></div>
<script type="text/javascript">
function fun() {
var i = limit;
var j = limit2;
limit = document.getElementById('limit').value;
limit2 = document.getElementById('limit2').value;
for (i = limit; i <= limit2; i++) {
c = 0;
for (j = 1; j <= i; j++) {
if (i % j == 0) {
c++;
}
}
if (c == 2) {
document.getElementById("result").insertAdjacentHTML('beforeend', i + '<br>');
}
}
}
</script>
Find the corrections below
function fun() {
/*var i = limit;*/
/*var j = limit2;*/
var limit = document.getElementById('limit').value;
var limit2 = document.getElementById('limit2').value;
var result = document.getElementById("result");
result.innerHTML = "Result: ";
for (var i = limit; i <= limit2; i++) {
var prime = true;
/* set j = 2 and NOT j = 1 */
for (var j = 2; j < i; j++) {
if (i % j == 0) {
prime = false;
break;
}
}
if (prime) {
result.insertAdjacentHTML('beforeend', i + ','); /* replaced <br/> with , to avoid page scroll */
}
}
}
fun(); /* test pupose only */
h1 {
margin: 0px;
}
<h1>enter the no.</h1><input type="text" id="limit" value="12">
<h1>enter the no.</h1><input type="text" id="limit2" value="55">
<button onclick="fun()">Submit</button>
<div id="result">Result:</div>
The text inserted inside an input is of type string , so you need to convert them to a number. Note the use of + document.getElementById("limit").value. The + convert a string to number.
The fill range function inside fun creates a new array starting from the the value inserted in the first text box upto the value inserted in second text box.
The array fill function will be used to create an array of length end-start+1 and initially filled with undefined. The map function will then create another array but undefined will be replaced by consecutive values.
filter is used to return only prime numbers
function fun() {
const fillRange = (start, end) => {
return Array(end - start + 1)
.fill().map((item, index) => start + index)
.filter((number) => {
for (var i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) return false;
}
return true;
});
};
let lowerRange = +document.getElementById("limit").value;
let upperRange = +document.getElementById("limit2").value
const primeNums = fillRange(lowerRange, upperRange);
document.getElementById("result").innerHTML = primeNums.join('<br/>')
}
<h1>enter the no.</h1><input type="text" id="limit">
<h1>enter the no.</h1><input type="text" id="limit2">
<button onclick="fun()">Submit</button>
<div id="result"></div>
If you want the fast implementation of the wiki link you provided in the question, here is the javascript for the same:
function getPrimesSuperFast(m, n) {
// Eratosthenes algorithm to find all primes under n
var array = [], upperLimit = Math.sqrt(n), output = [];
// Make an array from 2 to (n - 1)
for (var i = 0; i < n; i++) {
array.push(true);
}
// Remove multiples of primes starting from 2, 3, 5,...
for (var i = 2; i <= upperLimit; i++) {
if (array[i]) {
for (var j = i * i; j < n; j += i) {
array[j] = false;
}
}
}
// All array[i] set to true are primes
for (var i = m; i < n; i++) {
if(array[i]) {
output.push(i);
}
}
return output;
}
function getPrimes() {
var a = Number(document.getElementById("num1").value);
var b = Number(document.getElementById("num2").value);
var result = getPrimesSuperFast(a, b);
document.getElementById("res").value = result;
}
<input type="number" id="num1">
<input type="number" id="num2">
<button id="primes" onClick="getPrimes()">Get Primes</button>
<hr>
<textarea id="res" rows="20" cols="50">result will be displayed here...</textarea>
Using Sieve of Eratosthenes link: Rosetta Code
Alright so I am very new to JavaScript and Stack Overflow. I am still in high school but I have been working with Java and a few other languages for a while. Please give me any feedback that you can.
So I have recently started learning JavaScript and I was doing a project where you give the program text like an article or something and then give it key words and it return areas in the text where those words were mentioned. I already built this in java but I wanted to make it web based and have gotten pretty far but am having a problem with loading time. Essentially when I run this with a large amount of text it freezes for a while then eventually just refreshed the page and clears the data from the text field. Here's the code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<textarea id="input" rows="8" cols="100" ></textarea><br/>
<textarea id="keywords" rows="1" cols="50"></textarea><br/>
<textarea id="output" rows="8" cols="100"></textarea><br/>
<button id="read">READ!</button><br />
<script type="text/javascript">
document.getElementById('read').onclick = function(event) {
var input = document.getElementById('input').value.split(" ");
var keywords = document.getElementById('keywords').value.split(" ");
var found = "";
alert(input.length + " " + keywords.length);
for(i = 0; i < input.length; i++){
for(j = 0; j < keywords.length; j++){
if(input[i].toLowerCase().includes(keywords[j].toLowerCase())){
if(i >= 25 && input.length >= i + 40){
for(a = i- 25; a <= a + 40; a++){
found = found + input[a];
}
}else{
var length = input.length - i;
for(a = 0; a < length; a++){
found = found + input[a];
}
}
found += "\n\n";
}
}
}
output.value = found;
}
</script>
</head>
</body>
</html>
The loop
for(a = i- 25; a <= a + 40; a++){
outputs.push(input[a]);
}
is an infinite loop. a will always be smaller than a + 40. You probably wanted to say i + 40. But then your selection of output words is still strange, if not to say buggy. Assume your input is 10 words and you have a match in the 7th word. Then your program outputs the first 3 words - which doesn't include the match itself. You probably want to print x words before and y words after the match, but only if there are enough words to choose from. To this end, you could use the minimum and maximum function (see code below).
Some other things that become important when you want to improve the performance for larger texts are:
Whenever you concatenate a string with +=, a new object at a new
memory address is created, which is bad. Store the words you want to
output in an array and join them at the end with join().
You call toLowerCase() multiple times on the same string. If you have enough storage space, store the lowercase version of each word and reuse them.
In the code below, I have fixed these issues. The result is in no way meant to be optimal.
document.getElementById('read').onclick = function(event) {
var input = document.getElementById('input').value.split(" ");
var inputLower = new Array(input.length);
var keywords = document.getElementById('keywords').value.split(" ");
// create output array
var outputs = new Array();
// create arrays with lowercase words
for (var k = 0; k < input.length; k++) {
inputLower.push(input[k].toLowerCase());
}
var keywordsLower = new Array(keywords.length);
for (var k = 0; k < keywords.length; k++) {
keywordsLower.push(keywords[k].toLowerCase());
}
alert(input.length + " " + keywords.length);
for(var i = 0; i < input.length; i++) {
for(var j = 0; j < keywords.length; j++) {
if(inputLower[i].includes(keywordsLower[j])) {
for (k = Math.max(i - 10, 0); k <= Math.min(i + 10, input.length - 1); k++) {
// add at most 10 words before and 10 words after the matched word to the output
outputs.push(input[k]);
}
outputs.push("\n\n");
}
}
}
// join the words of the output with a space
output.value = outputs.join(' ');
}
I have learned in class how to make a function that generates all combinations of an inputted word. However, how to make it so that instead of a windowed prompt or alert popping up to enter the word and shows all combination on the prompt box, I want to display the result on the screen itself. How would i do that through the code i have already written?
This is my complete code:
<!DOCTYPE html>
<html>
<title>Combinations of a Word</title>
<body>
<script>
function combinations(str){
var substr = [];
for (var x = 0; x < str.length; x++)
{
for (var y = x + 1; y <= str.length; y++)
{
substr.push(str.substring(x,y));
}
}
return substr;
}
document.write(combinations(window.prompt("Please enter a word")));
</script>
</body>
</html>
Simply
<input type="text" id="word"/>
<div id="comb"></div>
JavaScript
function combinations(str) {
var substr = [];
for (var x = 0; x < str.length; x++) {
for (var y = x + 1; y <= str.length; y++) {
substr.push(str.substring(x, y));
}
}
return substr;
}
var input = document.getElementById('word');
var out = document.getElementById('comb');
input.addEventListener('keyup', function(e){
out.innerHTML = combinations(this.value).join(',');
});
FIDDLE
PS - your combinations code is wrong