Erdoğan Sönmez
Erdoğan Sönmez

Reputation: 45

JavaScript Loop Inside Loop Issue

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.

Upvotes: 2

Views: 94

Answers (3)

aliitascan
aliitascan

Reputation: 90

Check your len variable is have a value it must work with your codes.

Upvotes: 1

Francis Leigh
Francis Leigh

Reputation: 1960

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

Upvotes: 0

fdomn-m
fdomn-m

Reputation: 28611

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])
        }
    }
}

Upvotes: 1

Related Questions