JavaScript Loop Inside Loop Issue - javascript

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 />

Related

this code is supposed to delete duplicate values and delete empty spaces but it is deleting unique values as well

this code is supposed to delete duplicate values and delete empty spaces but it is deleting unique values as well.
cnt = 0;
for (let i = 0; i < this.fin.length; i++) {
for (let j = 0; j < this.fin.length; j++) {
if (this.fin[i] == this.fin[j]) {
cnt++;
if (cnt > 1) {
this.fin[j] = '';
}
}
if (j == this.fin.length - 1) {
cnt = 0;
}
}
}
this.ntmtg1 = true;
count = 0;
for (let j in this.fin) {
if (this.fin[j] == '') {
this.fin.splice(parseInt(j));
}
}
your logic is almost correct. The couple of mistakes you did are:-
In the for loop in the last part of your code, when you use for( let i in SomeCollection) 'i' will be the value and not index in the array. I think you want to access the index and not the value. I think you should use should use traditional for loop like for(int i =0; i<fin.length;i++).
You need to use splice with two arguments to delete some value from the array.
here is the link https://www.w3schools.com/jsref/jsref_splice.asp
You can do that in simply just one line of code with ES6 feature and Set :
var fin = ["Vivek","Vivek","Mak","Nik","Mak","Hir","Hari","Nur","Nik"];
var result = [...new Set(fin)];
console.log("Fin Total :" , fin.length , ", Result Total :" , result.length);
console.log(result);
Couple of fixes to your code
don't use for in if you're going to mutate the array
splice with only one argument splices from the index to the end of the array, so add a second argument, the length of the splice
in the code below, I omit this for simplicity
Also, I moved were cnt is defined, so no if condition gymnastics needed to reset it
const fin = [1,3,6,7,3,2,4,5,6,4,3,2,1,4,5];
for (let i = 0; i < fin.length; i++) {
let cnt = 0;
for (let j = 0; j < fin.length; j++) {
if (fin[i] == fin[j]) {
cnt++;
if (cnt > 1) {
fin[j] = '';
}
}
}
}
let count = 0;
for (let i = 0; i < fin.length; i++) {
if (fin[i] == '') {
fin.splice(i, 1);
--i; // we've removed an item
}
}
console.log(fin);
fin:any = ["OMAD","SVAC","SVCH","SVAD","LGAG","OMAM","OTBK","OTBH","LGAX","LGBL","SVAN","LGAD","SVAB","SKAP","LGRX","SVAA","SVAS","DNAS","EGEI","NCAT","SVBS","SVBL","SVFM","EPKG","OBBB","OBBS","OBKH","LTFD"
,"SVBC","SVBI","SVBM","SVBB","SVBO","TNCB","SVBZ","SKBU","SKBN","SVCI","SVCD","SVCL","SVCN","SVCC","SVCS","SVCO","SVCZ","SKGO","SVCP","NZCG","SVQM","SVCA","LGSA","MWCB","CYCK","SVCB","SVPI","MRCU","EKCN"
,"SVCR","SKCV","SVUR","SVCU","SVRB","TNCF","TNCC","LGTT","VRMD","OMDW","SVLL","SVED","SVRS","SVEM","SVJI","SVVG","LGEL","SVEZ","NZEV","EDTF","SVFT","VRMR","SKGB","SVGU","SVGD","SVGT","SVGI","SVQJ","EKHM"
,"SVQF","LSPK","SVQL"];

Javascript and html: button isn't working

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()">

Multiple Relations between two or more id's?

i have minimum of two select box in html form to insert through POST but user can add more select boxes.Now i have to show relations between each n every inserted id.
like we have inserted 1,2,3,4 id..so i want it inserted in a table in two column as
(1-2) (1-3) (1-4) (2-3) (2-4) (3-4)
plzz reply to this and tell some idea about this
any help??
Simply iterate your array and make couples of next elements in same array:
function calculate() {
var nums = document.getElementById('nums');
nums = nums
.value
.split(',')
.sort(function(a, b) {
return parseInt(a) - parseInt(b);
});
for (var i = 0; i < nums.length; i++) {
for (var j = i + 1; j < nums.length; j++) {
console.log('(' + nums[i] + ' - ' + nums[j] + ')');
}
}
}
<input type="text" placeholder="1,2,5,8" id="nums" />
<button onClick="calculate()">Calculate</button>

why is Object.keys show id as key?

HTML
<input type="checkbox"/>
<input type="button" id="btn" value="Click">
JS
var a = document.getElementsByTagName('input');
console.log(Object.keys(a));
for (var i = 0; i < Object.keys(a).length; i++) {
console.log(a[i]);
}
in console there are three keys is showing 0,1,'btn' . why is id showing in this object and how can i avoid this .
When you have a collection from getElementsByTagName() you can refer to an item either by its index or its ID.
So a[0] or a.btn.
I suspect you just want to iterate over all of them, which is just your basic for loop from Programming 101:
for(var i = 0; i < a.length; i++) {
// a[i]
}
That's what .length is there for!

Adding up all combinations of number in an array

I am trying to write a program in javascript that gets an unspecified number of numbers out of a html textarea and tries all combinations (adding all numbers with eachother) to see if it mathches a number you specified.
Now I can make an array out of the string in the textarea and using for loops I add these up (see below code). The problem how can you do this for an unspecified number of numbers that are to be added up (e.g. adding up 7 different number if you enter 7 numbers in textarea)? I was thinking of using a second array and, which gets the numbers to add up out of the first loop. And then make te lenght of the loop variable by using a for loop with the lenght of the array containing all numbers (lines in my example) as endvalue.
How can I fill in the values of this 2nd array, making sure all combinations are used?
By the way, I wanted this code because I am a auditor. Sometimes a client reverses a couple of amounts in one booking, without any comment. This code will make it a lot easier to check what bookings have been reversed
edit: The awnser of cheeken seems to be working I only have one remark. What if multiple sub sets of your power set added up result in the number you are looking for? e.g.:findSum([1,2,3,4,5],6) can result [1,2,3] but also [2,4] or [1,5]. is it possible to let the function return multiple sub sets?
Found the answer my self :)
I replaced code
return numberSet;
By
document.getElementById("outp").value=document.getElementById("outp").value+ numberSet +"\n";
Thank you very much Cheeken
One more additional question. How do i format the input for parsing that function? The code below doesn't seem to work. inp is the ID of the textarea where the input is (the numbers are seperated with a semicolumn. The variable ge works so there is no problem there (tested it with [1,2,3,4] and it worked. What is wrong with this code?
re edit:
found the solution. The array needed to be parsed as a floating number added this code.`
for (var i=0; i < lines.length; i++) {
lines[i]= parseFloat(lines[i]);
}
findSum(document.getElementById("inp").value.split(";"), ge);
Code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function powerset(arr) {
var ps = [[]];
for (var i=0; i < arr.length; i++) {
for (var j = 0, len = ps.length; j < len; j++) {
ps.push(ps[j].concat(arr[i]));
}
}
return ps;
}
function sum(arr) {
var total = 0;
for (var i = 0; i < arr.length; i++)
total += arr[i];
return total
}
function findSum(numbers, targetSum) {
var numberSets = powerset(numbers);
for (var i=0; i < numberSets.length; i++) {
var numberSet = numberSets[i];
if (sum(numberSet) == targetSum)
document.getElementById("outp").value=document.getElementById("outp").value+ numberSet +"\n";
}
}
function main()
{
ge= document.getElementById("getal").value;
findSum([1,1,0.5,0.1,0.2,0.2], ge);
}
</script>
</head>
<body>
<input type="button" onclick="main()" value="tel" /><input type="text" id="getal" /><br>
input<br><textarea id="inp" ></textarea><br>
output<br><textarea id="outp" ></textarea><br>
document.getElementById("inp").value.split(";")
</body>
</html>
More concretely, you're looking for a particular sum of each set in the power set of your collection of numbers.
You can accomplish this with the following bit of code.
function powerset(arr) {
var ps = [[]];
for (var i=0; i < arr.length; i++) {
for (var j = 0, len = ps.length; j < len; j++) {
ps.push(ps[j].concat(arr[i]));
}
}
return ps;
}
function sum(arr) {
var total = 0;
for (var i = 0; i < arr.length; i++)
total += arr[i];
return total
}
function findSum(numbers, targetSum) {
var numberSets = powerset(numbers);
for (var i=0; i < numberSets.length; i++) {
var numberSet = numberSets[i];
if (sum(numberSet) == targetSum)
return numberSet;
}
}
Example invocation:
>> findSum([1,2,3,4,5],6)
[1, 2, 3]
>> findSum([1,2,3,4,5],0)
[]
>> findSum([1,2,3,4,5],11)
[1, 2, 3, 5]
If you'd like to collect all of the subsets whose sum is the value (rather than the first one, as implemented above) you can use the following method.
function findSums(numbers, targetSum) {
var sumSets = [];
var numberSets = powerset(numbers);
for (var i=0; i < numberSets.length; i++) {
var numberSet = numberSets[i];
if (sum(numberSet) == targetSum)
sumSets.push(numberSet);
}
return sumSets;
}
Example invocation:
>> findSums([1,2,3,4,5],5);
[[2,3],[1,4],[5]]
>> findSums([1,2,3,4,5],0);
[[]]

Categories