3

I've read a few post here concerning my issue but I don't know how to apply that to my code since I don't work with an array or other object.

In Safari I get this error:

TypeError: undefined is not an object (evaluating '$('#related .expansion').data('handle').replace')

I have a function that populates a select dynamically, like so:

function expansieRubberSelect(){
  var url = $('#related .expansion').data('handle').replace('.html', '.ajax');
    $.getJSON(url, function(data){
        var select = '';
       $.each(data.variants, function (index, variant) {
          select += '<option value="'+variant.id+'" data-size="'+variant.title.replace(/\D/g,'')+'" data-price="'+variant.price.price_excl.toFixed(2)+'" data-priceincl="'+variant.price.price+'">'+variant.title+'</option>'
       });
       $("#related .expansion select").append(select);
    });
}

And then in my doc ready I call it like so:

 $(function(){
     expansieRubberSelect()
 });

I've read that missing an object is causing the problem obviously. However I don't have a clue how that would apply to my code. Do I need to change the select to an array or something? And then call in like expansieRubberSelect(mySelect)?

Any help appreciated!

Meules
  • 1,349
  • 4
  • 24
  • 71
  • 1
    When chaining you need to debug by checking that each link in the chain returns what you think it does. So, first of all check that `$('#related .expansion').length` does indeed confirm that the element exists. If it does, then check that `$('#related .expansion').data('handle')` does indeed return the URL you think it does. – Mitya Apr 07 '18 at 11:36
  • @Utkanos: Ok so you say that it may be `undefined` that's causing the error? – Meules Apr 07 '18 at 11:38
  • 1
    It means that, by the time you get to the `replace` part of the chain, you haven't ended up with the string that you were expecting. This probably means the element doesn't have the data piece that you think it does (from the `data()` link of the chain.) This needs to be ascertained before you do anything else. – Mitya Apr 07 '18 at 11:39
  • @Utkanos: Ok that seems to work indeed! Thx – Meules Apr 07 '18 at 11:44

1 Answers1

2

Thx to Utkanos' answer I managed to get it working. The idea is to check if the element exist. However you can also test for url to exist.

function expansieRubberSelect(){
 if($('#related .expansion').length){
  var url = $('#related .expansion').data('handle').replace('.html', '.ajax');
    $.getJSON(url, function(data){
        var select = '';
       $.each(data.variants, function (index, variant) {
          select += '<option value="'+variant.id+'" data-size="'+variant.title.replace(/\D/g,'')+'" data-price="'+variant.price.price_excl.toFixed(2)+'" data-priceincl="'+variant.price.price+'">'+variant.title+'</option>'
       });
            $("#related .expansion select").append(select);
    });
 }
} 
Meules
  • 1,349
  • 4
  • 24
  • 71