0

This is my js file content:

window.onload = function() {
    obj = document.getElementById("_accountwebsite_id");
    Event.observe(obj, 'change', function () {
        alert('hi');
    });
}

I want to fire the on change event for my dropdown: _accountwebsite_id . The prototype library it is loaded before this file. I got no errors in the console. Where am i wrong ? thx

1 Answer 1

1

You're doing a lot of extra work here that Prototype does for you. First off, setting the document's onload method not only is really old-school, it also will clobber any previously set observer on that event.

$(document).observe('dom:loaded', function( ... ){...});

...is the modern way to register one (or more) event listeners to the document load event.

Next, you're using getElementById here, which will work, but does not return a Prototype-extended object in some browsers.

$('element-id'); 

...will both get the element reference and extend it if your browser failed to respect every aspect of prototypal inheritance.

Finally, this whole thing can be made both simpler and more bulletproof by using a deferred observer. Imagine if your interface DOM was updated by Ajax -- that would make your observer miss the events fired by this select element, because it was not referring to the same (===) element, even if the ID matched.

$(document).on('change', '#_accountwebsite_id', function(evt, elm){
  alert(elm.inspect());
});

This observer will respond to any change event on an element with the correct ID, even if it was added after the observer was registered with the document.

1
  • I just spotted some typos, so reload before you use this directly!
    – Walter
    Nov 21, 2016 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.