Frash
Frash

Reputation: 67

Get values from same class buttons

I have a problem with this script.
I don't understand why Javascript doesn't recognize pdb[i].

let pbd=document.getElementsByClassName('pbda');

for (var i=0;i<pbd.length;i++) {
  pbd[i].addEventListener('click',function() {
    let xhttp=new XMLHttpRequest();
    xhttp.onreadystatechange=function() {
      if (this.readyState==4&&this.status==200) {
        document.getElementById('obxs').style.display='flex';
        document.getElementById('obxd').innerHTML=this.responseText;
      };
    };
    xhttp.open('POST','/ajax/orderdetails',true);
    xhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    xhttp.send('oid='+pbd[i].value);
  })
};


Error is -> Uncaught TypeError: Cannot read property 'value' of undefined at HTMLButtonElement.

Upvotes: 0

Views: 713

Answers (1)

Tushar Shahi
Tushar Shahi

Reputation: 20461

When your attached event listener actually runs, i has become pbd.length. So you are accessing an element which is not defined in your pbd array.

If you want to access an element in its event handler, you can use this.

let buttons = document.querySelectorAll(".man");
for(var i = 0 ; i < buttons.length;i++){
buttons[i].addEventListener("click",function(){
console.log(this);
console.log(i);
});
}
<button class="man">A</button>
<button class="man">B</button>
<button class="man">C</button>
<button class="man">D</button>
<button class="man">E</button>

Also you could have replaced var with let. let is block scoped so the i referred is the i from that iteration.

Upvotes: 1

Related Questions