views:

29

answers:

1

Hey all,

When I click in field, type text, and press return on keyboard it triggers the initializeTable function that refreshes page and gives error form[0] undefined. However, when I use change event to change dropdown selection, it doesn't cause this unexpected behavior. So I'm not sure why pressing return key in text field is causing all this. Thanks for response.

<script>
(function($){

var listview = $('#listview');

var lists = (function(){
    var criteria = {
        dropFilter: {
            insert: function(value){
                if(value)

                    return {"filter" : value}; 
            },
            msg: "Filtering..."
        },
        searchFilter: {
            insert: function(value){
                if(value)
                    return {"search" : value}
            },
            msg: "Searching..."
        }

    }
    return { 
         create: function(component){
            var component = component.href.substring(component.href.lastIndexOf('#') + 1); //sites
            return component;
        },
         setDefaults: function(component){
            var parameter = {};
            switch(component){
                case "sites":
                    parameter = {
                        'url': 'sites',                         
                        'order': 'site_num',
                        'per_page': '20'
                    }
            }
            return parameter;
        },
        getCriteria: function(criterion){
            return criteria[criterion];    

        },
        addCriteria: function(criterion, method){
            criteria[criterion] = method;   
        }
    }
})();  

var Form = function(form){
    var fields = [];
    $(form[0].elements).each(function(){  
        var field = $(this);  
        if(typeof field.attr('alter-data') !== 'undefined') fields.push(new Field(field));  
    })  
}

Form.prototype = {
    initiate: function(){
        for(field in this.fields){
            this.fields[field].calculate();  
        }
    },
     isCalculable: function(){  
        for(field in this.fields){  
                if(!this.fields[field].alterData){ 
                return false; 
            }
        } 
        return true;  
    } 
}

var Field = function(field){ 
    this.field = field;  
    this.alterData = true;  
    this.component = {'url' : window.location.hash.substring(window.location.hash.indexOf('#') + 1)};
    this.attach("change");  
    this.attach("keypress");  
}

Field.prototype = { 
    attach: function(event){
        var obj = this; //our Field object
        if(event == "change"){
            obj.field.bind("change", function(){ 
                return obj.calculate();
            })
        }
        if(event == "keypress"){
            obj.field.bind("keypress", function(e){  
                var code = (e.keyCode ? e.keyCode : e.which);
                if(code == 13){ 
                    return obj.calculate();
                }
            })
        }
    },
    calculate: function(){
        var obj = this, 
            field = obj.field,  
            component = obj.component,
            msgClass = "msgClass",
            msgList = $(document.createElement("ul")).addClass("msgClass"),  
            types = field.attr("alter-data").split(" "),  
            container = field.parent(),  
            messages = [];

        field.next(".msgClass").remove();  
        for(var type in types){  
            var criterion = lists.getCriteria(types[type]);  
            if(field.val()){ 
                var result = criterion.insert(field.val()); 

                container.addClass("waitingMsg");  
                messages.push(criterion.msg);  

                obj.alterData = true;  

                initializeTable(component, result);  

            }
            else { 
                return false; 
                obj.alterData = false; 
            }
        }
        if(messages.length){
            for(msg in messages){
                msgList.append("<li>" + messages[msg] + "</li");  
            }
        }
        else{
            msgList.remove();  
        }
    }
}

$('#dashboard a').click(function(){
    var currentComponent = lists.create(this);
    var defaults = lists.setDefaults(currentComponent);
    initializeTable(defaults);
});

var initializeTable = function(defaults, custom){

    var custom = custom || {};

    var query_string = $.extend(defaults, custom);

    var params = [];
    $.each(query_string, function(key,value){
        params += key + '=' + value + "&"; 
    })
    var url = params.substring(params.indexOf("url")+4,9);
    params = params.substring(params.indexOf("&")+1).replace(params.substring(params.lastIndexOf("&")),"");

    $.ajax({
        type: 'GET',
        url: '/' + url,
        data: params,
        dataType: 'html',
        error: function(){},
        beforeSend: function(){},
        complete: function() {},
        success: function(response) { 
            listview.html(response);

                var form = $('form');
                form.calculation(); 


        }
    })


}

$.extend($.fn, {   
    calculation: function(){

            var formReady = new Form($(this));

            if(!formReady.isCalculable){
                return false; 
            }

    }
})

 })(jQuery)
 </script>

Rather than going through whole script, the actual issue is with this:

if(event == "keypress"){
            obj.field.bind("keypress", function(e){ 
                var code = (e.keyCode ? e.keyCode : e.which);
                if(code == 13){ 
                    return obj.calculate();
                }
            })
        }
    }
A: 

Finally, I got it to work this this:

            if(event == "keypress"){
            obj.field.bind("keypress", function(e){ 
                var code = (e.keyCode ? e.keyCode : e.which);
                if(code == 13){ 
                    e.preventDefault();
                    return obj.calculate();
                }
            })
        }
    },

Hence, we first prevent default and then execute our custom function.

JohnMerlino
Not that it stops anything from working, but you might like to know that jQuery normalizes e.which, so that it can be used cross-browser. You don't need to check e.keyCode as well.
Ender