Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling javascript class function from onchange attribute

I have a simple class that has a few methods(for now). I can instantiate it and call the init function, but I cant call another method from the onchange attribute.

here is the class:

var ScheduleViewer = (function() {
var options = {
  container: 'trip_stops',
  schedule: {}
};

function ScheduleViewer (){};

ScheduleViewer.prototype.init = function(params) {
  $.extend(options, params);
  // setTimeout(function() {
  //   ScheduleViewer.addListener(options);
  // }, 3000);
  this.addListener(options);
}

ScheduleViewer.prototype.getSchedule = function(trip_id) {
  var _id = trip_id;
  console.log(_id);
}

ScheduleViewer.prototype.addListener = function(options) {
  console.log("adding listener");
   var _id = options.select_id;
   console.log($('#train_select').length);// zero assuming timing issue
   $('#'+_id).on('change', function() {
     alert("changed");
   })
}
return ScheduleViewer;
})();

the call

<div id="trip_stops" class="trip_options">
        <% if (trips.length > 0) {  %>
            <%
                var params = {
                schedule: schedule
              };
              var scheduler = new ScheduleViewer();
              scheduler.init(params);
            %>
            <select id="train_select">
                <option value="0" selected disabled>Select a train</option>
                <% $.each(trips, function(index, val) { %>
                    <option value="<%= val.trip_id %>">
                        <%= val.train_num %> Train
                    </option>
                <% }); %>
            </select>
        <% } else { %>
            No trips scheduled.
        <% } %>
    </div>

Note that Im using jqote for templating.

I get the log from the init call, but then fails in the onchange with Uncaught ReferenceError: scheduler is not defined. Im not sure what Im doing wrong. Any pointers?

Thanks

EDIT: I made an attempt to add a listener that gets called at initialization. Im assuming that because of timing issues the listener is not getting bind. Now this is where my inexperience comes in play I tried to setTimeout but the function call is not happening as is.

like image 814
LouieV Avatar asked Oct 21 '22 04:10

LouieV


1 Answers

I don't know why this may not work, but you shouldn't really use inline styles/functions anyway.

Why don't you try and get the element in your script the apply the onchange function to it.

var scheduler = new ScheduleViewer();
    select = document.getElementById('train_select');

scheduler.init(params);

select.onchange = function() {
   scheduler.getSchedule(this.value)
};
like image 165
iConnor Avatar answered Oct 23 '22 18:10

iConnor