jquery from external file not loading - javascript

So I know this question has been asked many times but I can't seem to get this working, even though it looks correct to me. My jquery functions from an external file aren't loading properly.
My tableMethods.js external file looks like
$(function(){
// Write FITS
function writeFits(){
var data = $('.sastable').bootstrapTable('getData');
var name = $('#fitsname').val();
$.getJSON($SCRIPT_ROOT + '/writeFits', {'data':JSON.stringify(data),'name':name},
function(data){
$('#fitsout').text(data.result);
});
}
// Delete rows from data table
function deleteRows(){
var $table = $('.sastable');
var $delete = $('#delete');
var ids = $.map($table.bootstrapTable('getSelections'), function (row) {
return row.id
});
$table.bootstrapTable('remove', {
field: 'id',
values: ids
});
}
})
My html header looks like
<script type="text/javascript" src="/static/js/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap-table.js"></script>
<script type='text/javascript' src="/static/js/tableMethods.js"></script>
When I check the inspector, it says the file has loaded yet when I click my button that looks like
<button id="delete" class="btn btn-danger" type='button' onClick='deleteRows()'>Delete Rows</button>
I get the error
Uncaught ReferenceError: deleteRows is not defined

This is a scoping problem. You have to move your functions outside of $(function() { ... })
In JavaScript, anything exclusively defined within a function, generally stays within a function:
var x = 3;
(function() {
var y = 1;
})();
console.log(x); // 3
console.log(y); // error
So if you’re defining a function within a function, you can only invoke it from that function you have defined it in. When trying to invoke it from anywhere else, the inner function will seem undefined.
In your case, you can simply remove the wrapper function:
$(function() { // Delete this...
...
}); // And this
For more information, read You Don’t Know JS: Scope & Closures

Related

Trying to access ejs array in a js file

I send info to the client that contains an array and I only show 3 elements of the array because I want to have a pagination effect. I wanted to write the pagination code in a js file
in file.js
$(function(){
$(".pageLinks a").on("click", function(e){
e.preventDefault();
var pageNum = $(this).attr("id")
var test = JSON.stringify(populated) // I wanted populated to be the array from node
//doesn't have to have the stringify part
// I know I can't do this prob bec. it's not in an ejs file but I wanted something like that
console.log(test)
})
})
I'm able to access it in the ejs file
<% var index = Math.floor( populated.reviews.length /3)%>
<div class = "pageLinks">
<%for(var i = 0; i < index; i++){%>
<%= i + 1 %>
<%}%>
</div>
</div> <!--reviewSide-->
You're right, you can't get to the raw object in the (static) js file in the same way.
However, you can populate it to a global variable in your ejs file like this:
<script type="text/javascript">
var populated = <%-JSON.stringify(populated)%>;
</script>
which you can then either check for in the click handler like this:
$(function(){
$(".pageLinks a").on("click", function(e){
e.preventDefault();
var pageNum = $(this).attr("id")
if (typeof(populated) != "undefined"){
// you want to check to make sure this exists before trying to use
// it, just in case someone manages to click a page link before the
// code in your .ejs file has run.
var test = JSON.stringify(populated)
console.log(test)
}
})
})
...or pass to the external file.js when you load, as long as you're exposing something to the global scope that it can call. Your current script wraps everything in an anonymous function, but you could wrap it in a named function like this:
.ejs file:
<script type="text/javascript">
initialiseMyAwesomeFunction( <%-JSON.stringify(populated)%> );
</script>
.js file:
function initialiseMyAwesomeFunction(populated){
$(function(){
$(".pageLinks a").on("click", function(e){
e.preventDefault();
var pageNum = $(this).attr("id")
var test = JSON.stringify(populated)
console.log(test)
})
})
}

Function out of scope?

I have a function defined as follows:
window.onload = function() {
var ids = document.getElementById("idname");
function myFunction(){
/...*use ids var in here*./
}
}
I am trying to call myFunction from button onclick in html:
<button onclick="myFunction();"></button>
But it says myFunction is not defined. I understand because this is inside window.onload. How can I fix this? I need window.onload because I need to use document.getElementById("testID") to get content.
I need window.onload because I need to use document.getElementById("testID") to get content
No, you don't need window.onload. You simply have to put the code somewhere after the element with ID testID in the document.
Example:
<div id="testID"></div>
<script>
var ids = document.getElementById("testID");
function myFunction(){
/...*use ids var in here*./
}
</script>
However, if you want to keep using window.onload, then I suggest to not use inline event handlers, but bind the handler with JS:
window.onload = function() {
var ids = document.getElementById("testID");
ids.onclick = function(event){
/...*use ids var in here*./
}
};
(that might be a good thing to do anyway).
Lastly, you can get the a reference to the element inside the event handler using this or event.target:
<div id="testID"></div>
<script>
document.getElementById("testID").onclick = function(event) {
// access element via `this` or `event.target`
};
</script>
Learn more about event handling.
You defined it within a function so it's locked to that scope. Maybe you want to define it outside of that:
function myFunction() {
var ids = document.getElementById("idname");
// ...
}
window.onload = function() {
// ...
}
As a note, this is extremely old-school JavaScript. You could clean this up considerably using something like jQuery which would look something like this:
$(function() {
// Any initialization after page load.
});
function myFunction() {
var ids = $('#idname');
// ...
}

Use JavaScript to go to a page and automatically do a function on that page

Hopefully this is a no-brainer for all you experts, but I can't find the answer. I want to click on an element on Page A that will take me to Page B and automatically perform a function (here it's called showGrp) defined on Page B. On Page A, I want to click something like this (obviously, it doesn't work, but I think it conveys the idea):
<span onclick="location.assign('http://happy.com/pageB.htm').('showGrp(); return false;')">
<h2>Search Topics</h2>
</span>`
Short answer: there's no way to do that. You can't tell a new page to run a function through an old page
Long answer: You can, however, set up page B so it will know that if the request URL contains a certain argument in its GET data, it will run showGrp. i.e.:
going to http://happy.com/pageB.htm will do nothing
going to http://happy.com/pageB.htm?showGrp=1 will run function
You can use this function like so:
// put this wherever you want to run this - most probably when the page is loaded
if (getParameterByName('showGrp')) {
showGrp();
}
You could do something like this:
PageA:
<html>
<body>
<a href="pageB.html?f=showGrp">
<h2>Search Topics</h2>
</a>
</body>
</html>
PageB:
<html>
<head>
<script type="text/javascript">
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
}
var init = {
showGrp: function () {
console.log("Hello world!");
},
otherFunc: function() {
console.log("Lalala!");
}
};
init[getQueryVariable("f")]();
</script>
</head>
</html>
By making this you are able to execute whatever function you want just passing it name as an argument to the pageB's URL.
I would just put the code that you want to run in the window onload function on page B. I think that will do what you want.
window.onload = function() {
showGrp();
};
See a description of onload at the Mozilla Developers Network.
Page A should look like:
<div id = "yourclickobject" onclick="pageB.html"> Some random text </div>
Page B:
<head>
<script>
var myFunction = function(){
alert("hello world");
}
myFunction();
</script>
</head>
Does this help?
As soon as you go on page B myFunction is called. All you need to do is put it in the head

Set var value from other JavaScript file using jQuery

I have a two JavaScript files:
Main.js
Pmt.js
I'm also using thick box (Ajax call)
in Main.js
$(document).ready(function() {
var cnt=0;
$("#btnPmt").click(function(){
cnt=cnt+1;
tb_show('Void Transaction','pmt.jsp?height=310&width=400', null);
});
});
The Pmt.js file is included in pmt.jsp as
<script src="js/Pmt.js" type="text/javascript"></script>
in Pmt.js
$("#btnPmtClose").click(function(){
cnt=0;
parent.tb_remove();
});
How we can reset the value of var cnt in Pmt.js that decalred in Main.js?
The above is not working, when I close the thickbox, I find the incremented value, not zero that set on close, even Ajax call.
in Main.js make cnt as global var by moving it outside any function :
var cnt=0;
$(document).ready(function() {
...
})

Why cant my anchor fire this javascript object?

I have a page with a linked javascript object:
//the constructor function
function NewsScroller() {
}
//now put some config objects using the JSON structure
NewsScroller.prototype.config = {
serviceUrl : '/NewsProvider.svc/rest/GetNews/',
pageIndex : 0
}
//the argumented constuctor for this object
NewsScroller.prototype.init = function () {
this.getNews(this.config.pageIndex);
console.log(this.config.pageIndex);
}
NewsScroller.prototype.decreasePage = function () {
console.log('current page index ' + this.config.pageIndex);
}
Then I have the page ready declaration:
<script>
$(document).ready(function () {
var newsScrollerForPage = new NewsScroller();
newsScrollerForPage.init();
newsScrollerForPage.decreasePage();
});
</script>
Which produces the result:
current page index 0
I want to call the function from an anchor tag so I have:
<div class="scroller-left">
<a id="scroller-left-a" href="javascript:newsScrollerForPage.decreasePage();">
<img src="/Images/Left-Scroller.jpg"/>
</a>
</div>
But when I click the anchor I get:
newsScrollerForPage is not defined
Why is this? Surely I should be able to call the object and function just like I did in the .ready method?
You define the newsScrollerForPage inside the ready function with local scope (by using "var"), you can't use it outside of there except if you define a function in the same scope which uses it (scope is evaluated from where functions are defined, not from where they are called).
You can quickly fix the issue by taking away the var from before it (making it more global rather than local in scope) but I wouldn't suggest this as the best solution.
Better would be to link up the anchor like this:
$(document).ready(function () {
var newsScrollerForPage = new NewsScroller();
newsScrollerForPage.init();
newsScrollerForPage.decreasePage();
document.getElementById("scroller-left-a").onclick=function()
{
newsScrollerForPage.decreasePage();
return false;
}
});
and removing the href from the HTML element.

Categories

Resources