Reputation: 388
I am having variables that reference html ID's like
<div data-role="footer" id="ftrPaxFlight">
<h4>© 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?
Upvotes: 0
Views: 1281
Reputation: 942
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);
}
Upvotes: 1
Reputation: 108500
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 );
});
Upvotes: 2
Reputation: 471
use
var ftrPaxFlight = $('#ftrPaxFlight').val()
and declare
<script>
var ftrPaxFlight;
$(document).ready(function() { .......
as global before ready function.
Upvotes: 0