2

There are multiple pages on my web-project working with exactly same JS functions. I was copying and pasting same functions to all pages' js files. But recently seperated common functions to another js file named common_fns.js, for every page created just selector cached variables and placed at the top of every page in order some_page.js, common_fns.js . Something like that

some_page.js

$(function() {
    var closer=$("#nlfcClose"),
    NewFormContainer=$("#NewLessonFormContainer"),
    opener=$("#nlfcOpen"),
    NewForm=$("#NewLessonForm"),
    OpsForm=$("#LessonOps"),
    SelectBox=$( "#courses" ),
    SelectBoxOptions=$("#courses option"),
    jquiBtn=$(".jquiBtn"),
    AddOp="AddLesson",
    DelOp="DelLesson";
});

common_fns.js

$(function() {
    SelectBoxOptions.text(function(i, text) {
        return $.trim(text);
    });

    SelectBox.combobox();
    jquiBtn.button();

    closer.button({
        icons: {
            primary: "ui-icon-closethick"
        },
        text: false
    }).click(function(){
        NewFormContainer.slideUp("slow");
    });

    opener.click(function(){
        NewFormContainer.slideDown("slow");
    });

    NewForm.submit(function(){
        var querystring = $(this).serialize();
        ajaxSend(querystring, AddOp);
        return false;
    });


    OpsForm.submit(function(){
        var querystring = $(this).serialize();
        ajaxSend(querystring, DelOp);
        return false;
    });
});

It was working when I copied and pasted common functions to every pages' file. But now it doesn't: Firebug shows error message undefined SelectBoxOptions even for first function. What am I missing? Only way to copy-paste same functions into every pages' js file?

heron
  • 3,611
  • 25
  • 80
  • 148

1 Answers1

5

You are declaring local variables inside the event handler, that's why you can't use them in the next event handler.

Declare the variables outside the function:

var closer, NewFormContainer, opener, NewForm, OpsForm, SelectBox, SelectBoxOptions, jquiBtn, AddOp, DelOp;

$(function() {
    closer = $("#nlfcClose");
    NewFormContainer = $("#NewLessonFormContainer");
    opener = $("#nlfcOpen");
    NewForm = $("#NewLessonForm");
    OpsForm = $("#LessonOps");
    SelectBox = $( "#courses" );
    SelectBoxOptions = $("#courses option");
    jquiBtn = $(".jquiBtn");
    AddOp = "AddLesson";
    DelOp = "DelLesson";
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005