0

I am having variables that reference html ID's like

<div data-role="footer" id="ftrPaxFlight">
    <h4>&#169; 2012, BT</h4>
</div>

and I am having a javascript embedded in html using jQuery which is like

<script>
  $(document).ready(function() {
            var ftrPaxFlight = $('#ftrPaxFlight');
    var butMainLogin = $('#butMainLogin');
    var butMainSetup = $('#butMainSetup'); 
       .....
      butMainLogin.bind("click", function() {
           getChangeFtr();
    });

Where getChangeFtr is a function located in an external .js file. I want to seperate the logic from UI. This file is also included under tags

function getChangeFtr(){
     alert("Ftr will be changed " + ftrPaxFlight);
 }

When the button is clicked .. the method getChangeFtr() is called, I am getting an error

TypeError - ftrPaxFlight is undefined.

Can someone guide me to the right way of passing variables to multiple javascript files using jQuery?

3 Answers 3

2

There are many ways of doing this, and there is no "right way". You can use global variables, a global namespace/singleton or simply pass objects between functions using arguments. In your case I would use arguments:

function getChangeFtr( elem ){
    alert("Ftr will be changed " + elem);
}

And:

butMainLogin.bind("click",function() {
    getChangeFtr( ftrPaxFlight );
});
Sign up to request clarification or add additional context in comments.

3 Comments

Hi David, I tried this method. I am getting "Object" instead of the value in ftrPaxFlight. if I use ftrPaxFlight.val() I get a very strange block of code dumpted in my alert box. any way to get the contents of the ftrpaxFlight ?
I tried using ftrPaxFlight.innerHtml. It gives me it is undefined !
Thank you a lot for the tip. I am just learning JQuerry and JS. I got this working by using ftrPaxFlight.val(). Cheers
1

Your ftrPaxFlight variable is declared inside of the scope of the document ready function. You would need to declare it in the global scope in order for your global methods to access the variable.

var ftrPaxFlight;
$(document).ready(function(){
    ftrPaxFlight = $('#ftrPaxFlight');
    //....etc
}

function getChangeFtr(){
    alert("Ftr will be changed " + ftrPaxFlight);
}

1 Comment

Hi Bergs, Thanks for your answer. I tried this too. It give me.. Ftr will be changed [object Object]. Any idea what must I do to get the value of ftr ? thanks
0

use

var ftrPaxFlight = $('#ftrPaxFlight').val()

and declare

<script>
var ftrPaxFlight;
$(document).ready(function() { .......

as global before ready function.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.