Marc
Marc

Reputation: 75

javascript getelementsByClassName - undefined []

Background: I bought this WordPress plugin for event bookings. Apparently the author did not feel it was necessary for things like price updates after adding more than 1 ticket or applying coupons and so I am trying to write a quick and dirty solution myself. The price it charges is correct, but I think people should see the final price before submitting their credit cards. You can see this in action here (just try adding more than 1 ticket) https://hellbentbbq.ca/events/ultimate-pork/

My quick and dirty hack approach is to 1) Watch for the ticket select to change 2) Watch for coupon code to be successful

I am starting with #1 and trying to get the following to work:

`document.getElementsByClassName('em-ticket-select').onchange=function(){ updatePrice() };
console.log(document.getElementsByClassName('em-ticket-select'));

function updatePrice(){
        price=document.getElementById('theprice');
        alert(price);
}
`

I've added the console.log just so I can understand specifically what I am selecting, but for some reason I can't seem to select any of the items in the html collection?

I thought I could go:

document.getElementsByClassName('em-ticket-select')[0] and get the element I want but apparently not - result is undefined. Without [0] here is what is logged to the console:

HTMLCollection[0]
0
:
select#em-ticket-spaces-5.em-ticket-select
em-ticket-spaces-5
:
select#em-ticket-spaces-5.em-ticket-select
em_tickets[5][spaces]
:
select#em-ticket-spaces-5.em-ticket-select
length
:
1
onchange
:
()
__proto__
:
HTMLCollection

Any direction on where I am going wrong is appreciated.

I realize it would be easier if I could select the element by ID, but the ID is dynamically generated and I am really just trying to make a quick dirty bolt on JS to solve this instead of rewriting or trying to figure out what someone else was doing in their code.

Upvotes: 2

Views: 902

Answers (1)

Michael Coker
Michael Coker

Reputation: 53674

To attach an event listener on the array like object returned via getElementsByClassName, loop through them and attach the listener to each one.

var selects = document.getElementsByClassName('em-ticket-select');
function updatePrice(el) {
  console.log(el.value);
}
for (var i = 0; i < selects.length; i++) {
  selects[i].addEventListener('change',function() {
    updatePrice(this);
  });
}
<select class="em-ticket-select">
  <option>foo</option>
  <option>bar</option>
</select>

<select class="em-ticket-select">
  <option>foo</option>
  <option>bar</option>
</select>

<select class="em-ticket-select">
  <option>foo</option>
  <option>bar</option>
</select>

Upvotes: 2

Related Questions