Search code examples
jqueryprototypejs

Initialization function of prototype is working but change event not working


I have a file named abc.js whose code is

var Calculator = Class.create();
Calculator.prototype = {
    initialize: function () {
      alert('initialize');
    },    
    calculate: function () {
      alert('Calculate on change');
    }       
}

and a html file having dropdown

<select name="calculator_select" id="calculator_select" onchange="calculator.calculate()">

and i have created calculator object

 var calculator = new Calculator();

When page gets loaded,initialization function of Calculator.prototype is called and it alerts initialize but onchange of dropdown calculator.calculate() doesnot respond.


Solution

  • Here's a working example: http://jsfiddle.net/xRXE4/

    A few hints:

    -stop adding events inline (use addEventListener, jquery's on)

    -use console.log and open up console (F12)

    -include the code that uses DOM elements inside $(document).ready()

    var Calculator = Class.create();
    
    Calculator.prototype = {
        initialize: function () {
          console.log('initialize');
        },    
        calculate: function (e) {
          console.log('Calculate on change');
        }       
    }
    
    var calculator = new Calculator();
    
    var selectEl = document.getElementById("calculator_select");
    
    selectEl.addEventListener('change', function() {
         calculator.calculate();
    });
    

    http://api.jquery.com/on/

    addEventListener vs onclick