Search code examples
javascriptfirefoxyui

Displaying which id is missing


I'm having problems to make the same web apps work for different versions of Firefox :

var col = [{'id': 'id1'}, {'id': 'id2'}, {'id': 'id3'},{'id': 'id4'},
                {'id': 'id5'}, {'id': 'id6'}, {'id': 'id7'}, {'id': 'id8'}];
doSomething(col);

if id5 doesn't exist my page displays fine in FF8 but in FF 3.5 its not the case.

Is there a way to report or test when an id doesn't exist and display its name (because even in browser console it doesn't display which id is ) ?

EDIT

var col = [{'id': 'id1'}, {'id': 'id2'}, {'id': 'id3'},{'id': 'id4'},
                    {'id': 'id5'}, {'id': 'id6'}, {'id': 'id7'}, {'id': 'id8'}];
     YAHOO.util.Dom.batch(col, desactivateBtn );

    var desactivateBtn = function(btn){
            YAHOO.widget.Button.getButton(btn.id)._setDisabled(true);
    };

I'm using YUI and YAHOO.util.Dom.batch is just so that it applies desactivateBtn on all buttons with the ids in col (it's similar to jQuery's $.each method)

Thanks


Solution

  • You're trying to access a property or method on an element that isn't found.

    Change:

     var desactivateBtn = function(btn){
           YAHOO.widget.Button.getButton(btn.id)._setDisabled(true);
       };
    

    To:

     var desactivateBtn = function(btn){
           var elem = YAHOO.widget.Button.getButton(btn.id);
           if(elem) elem._setDisabled(true);
       };
    

    I've encountered a similar problem with IE swallowing what other browsers would consider an exception. The problem stemmed from using eval (it was legacy code, not written by me). I haven't looked at YAHOO's library, but I wonder if the getButton method uses eval internally?

    edit: If you want to display which items are missing, there's no easy way to do this across browsers since IE8 doesn't have console.log. You could choose to write the output to a debug div element or alert with the message. I'd probably go with the debug div element.

    var DEBUG = true;
    window.DEBUG_OUTPUT = null;
    
    if(DEBUG) {
       window.DEBUG_OUTPUT = /* create div, append to whatever element */
    }
    

    Then, you can modify your function to something like:

    var desactivateBtn = function(btn){
        var elem = YAHOO.widget.Button.getButton(btn.id);
        if(elem) { elem._setDisabled(true); }
        else { window.DEBUG_OUTPUT.innerHTML = window.DEBUG_OUTPUT.innerHTML + ('' + btn.id);
    };
    

    A couple things to note:

    1. I don't like adding to the window object, but for console/debug I think it's alright.
    2. I have ('' + btn.id) to coerce non-string ids (like 1, 2, etc.) to strings. I'm not sure if this is a problem any more, but I encountered a bug long ago in some browser that setting innerHTML = 3 would cause an error since 3 isn't a string. I haven't had time to test if this is still a problem in any of the major browsers.

    edit2: even better, wrap the btn.id in <p></p> tags.