If I have this code on my page then it works
index.html
<input type="file" name="data[Post][picture]" hidden="1" onchange="uploadPhoto(this.files)" id="PostPicture"/>
script.js
function uploadPhoto(files){
//TODO
console.log(files);
}
but that code requires me to put uploadPhoto() function out of jquery $() function. I have certain problems with variable scope and so I don't want to get my function outside of document.ready function.
for that I did something like this
$(function(){
var uploadPhoto = function(){
//TODO
console.log($('#PostPicture').files);
};
$('#PostPicture').on('change',uploadPhoto);
});
and it logs undefined in the console.
The jQuery results set does not have a files attribute, you need to access the element directly:
var files = $("#fileInput")[0].files;
or
var files = $("#fileInput").prop('files');
source: https://stackoverflow.com/a/13747921/441907
Related
I have javascript file called screener.js
function ScreenerPage() {
function onScreenListChange() {
do stuff
};
}
from the index.html file I include the javascript file like this:
<script type="text/javascript" src="./js/screener.js"></script>
Then later in the head section of index.html I instantiate the screenerPage object like this:
<script type="text/javascript">
$(document).ready(function () {
screenerPage = new ScreenerPage();
}
</script>
Then down in the body section there is a select with onchange event that calls
<select id="screenList" onchange="screenerPage.onScreenListChange()">
but the browser shows error:
Uncaught TypeError: screenerPage.onScreenListChange is not a function
What am I doing wrong?
The way javascript works is it has objects and the way of which they are created matter!
Here is the way i've found that works for this kind of thing
screener.js
var ScreenerPage = function() {
this.onScreenListChange = function() {
//do stuff
console.log("test")
}
}
Later on
var a = new ScreenerPage();
a.onScreenListChange();
if you have any questions on how it works feel free to try to message me!
The reason it does not work is that you're having a scope issue.
The function ScreenerPage is defined in the global scope, meaning it is accessible anywhere. Now inside that function you define a local function called onScreenListChange.
You are able to do that, but that function only exists within the scope of the function you defined it in.
When I look at your function, I think you want to use classes. A class is a single name that can have multiple variables / methods to do a specific task.
class ScreenerPage {
constructor(text){
this.onScreenListChange(text) // Call this "method" on object creation.
}
onScreenListChange(text) {
console.log(text ? text : 'do stuff');
};
}
var a = new ScreenerPage('hi'); // now watch your console log.
a.onScreenListChange();
I want to execute a function which was defined in the start of the script, lets call this function initialize. This function also uses a variable, lets call it login, which is defined by a php file that includes my jquery script file after defining the variable login.
php/html:
<script type="text/javascript">
login = '<?php echo $login; ?>';
...
</script>
<!-- script is included -->
<script type="text/javascript" src="script.js"></script>
jquery:
function initialize(){
$("." + login).remove();
}
jQuery.moreContent = function moreContent()
{
//more content is loaded
...
initialize();
}
the moreContent function is then loaded, I can see more content appearing on my screen but initialiye is not loaded. only if I use a function like resize (in the end of the script.js file) it works
jquery (in the end of script):
//load function initialize
initialize();
//this function doesnt work too, I tested if it even loads and it does (used a number that was increased by one whenever function was loaded which actually happened...)
//however the wished element with the class of variable login is not removed
//resize function
$(window).resize(initialize);
//this one suddenly works
...
I have no idea why it suddenly works with the other function and why it doesnt work in the other cases
You need to wrap your code and make it run once the document is ready, like this:
$(document).ready (function(){
// run all your functions here
});
Maybe the variable login is empty in the other function, or you are giving thst a different value.
Try with a global variable to test it, like
window.login = script_php
And try again, in this ways, the login variable is global, or pass this variable as a parameter in the function.
the moreContent function is then loaded, I can see more content appearing on my screen but initialize is not loaded.
That is not exactly what happened. You have attached a function as method directly to jQuery object but did not invoke it,
jQuery.moreContent = function moreContent()
{
//more content is loaded
...
initialize();
}
You won't get any fruitful benefit from doing it this way. You have just added a method to an object (jQuery in this case) which is not invoked yet. In any case you do not need to add it as a method to jQuery object itself. You can do it easily without this as following.
function initialize(){
$("." + login).remove();
}
// this is a global function right now, use it anywhere you want.
function moreContent()
{
//more content is loaded
...
initialize();
}
// document ready...
$(function(){
moreContent();
});
You can rearrange the code and remove the unnecessary function layers (depends upon your code structure) and use it like this.
$(function(){
// more content...
initialize();
});
if I use a function like resize (in the end of the script.js file) it works
It worked because it is attached directly to window by jQuery on resize event.
$(window).resize(function(){
// The code inside will work whenever user resizes the window.
// It does not need to be hooked up inside document ready.
});
I have no idea why it suddenly works with the other function and why it doesnt work in the other cases
The reason it worked inside event handlers is because you hooked up your functions to run as a callback function to them. You have set it up correctly in click or resize event but not in load event. In load event you just created a function and added the it as a method to jQuery object but did not invoke it. The only and only way a function runs inside JavaScript is when you suffix parenthesis.
function demo()
{
// do something...
return "Done";
}
// a named function "demo" got created, but not invoked.
demo; // returns the whole function literal, not invoked yet.
demo(); // invoked, returns Done
So continuing from this, adding it as a method to jQuery will not load it, until you invoke it e.g.
jQuery.myNewMethod = function myNewMethod() {
return "Hey there :)";
}
// jQuery loaded, but where is my method ?? (#__#)
// let's invoke it then...
jQuery.myNewMethod(); // invoked the function using parenthesis!
// returns "Hey there :)"
// Now i can see you go (^__^)
Hello I have problem with existing javascript code.
The background is that some of JSP Tags automatically include JS function, and then some of html elements need to run this functions.
But the point is that there a lot of html elements that need to use included JS function, and there will be very hard to modify each separate element to configure which function it should run.
Lets consider simple example: we have JSP Tag that generate table
<table id="automaticallyGeretatedId">
<tr>
<td></td>
</tr>
</table>
and this include some JS function
function removeItemFromTable(){
//modify automaticallyGeretatedId
}
function addItemToTable(){
//modify table, add values and so on..
}
then we have some html external buttons or/and div-s that have method with constant name "clearData" but the JS is a part of HTML page
sometimes in this way (embedded in Html)
<script>
function clearData(){/*some code*/}
</script>
and sometimes in included file as
function clearData(){ //some code
}
So my question is: is other way than modify each simple clearData in code, to ensure that each time when clearData function will be run, the function removeItemFromTable() will be also run?
I mean can I search for clearData function and append after it call to removeItemFromTable function? And where should be this operation done, what is the best way to do this?
Lets suppose that each time when clearData() function appear the function removeItemFromTable() also will be included.
Finally I decided to use described at this link technique:
Adding code to a javascript function programmatically
I set up at document ready to search function clearData()
$( document ).ready(function() {
decorateClearData();
});
and code in function decorateClearData();
function decorateClearData() {
clearData = (function() {
var cached_function = someFunction;
return function() {
cached_function.apply(this, arguments); // use .apply() to call it
// and my new code:
removeItemFromTable();
};
}());
}
This works because clearData is global function, and maybe this is not pragmatic way but I didn't have other ideas.
I have an html textbox and get the value from it with the following code:
$('#getTextBoxValue').on("click", function(){
var value = $("#textbox1").val();
});
I then attempted to pass that value to a different function
function loadPdf(pdfPath) {
var pdf = PDFJS.getDocument(pdfPath);
return pdf.then(renderPdf);
}
loadPdf(value);
But the value isn't being passed. I then attempted to do the following:
$('#getTextBoxValue').on("click",
function(){
var value = $("#textbox1").val();
alert('The Value in Textbox is '+value);
});
to see if the value was displayed, but that didn't work either (didn't get any output)
EDIT: I do get an error in the console:
ReferenceError: $ is not defined
And if I remove the $ it says ('#getTextBoxValue).on is not a function
$ is a reference to jQuery. This works for me if jQuery is included:
<input id="textbox1"></input>
<button id="getTextBoxValue">Get value</button>
$('#getTextBoxValue').on("click",
function(){
var value = $("#textbox1").val();
alert('The Value in Textbox is '+value);
});
JSFiddle example
If you wanted to do it without jQuery, use document.getElementById("textbox1").value; and add the onclick either inline or via normal javascript also:
document.getElementById("getTextBoxValue").onclick = function(){
var value = document.getElementById("textbox1").value;
alert('The Value in Textbox is '+value);
};
After you get that to work, just replace the alert with loadPdf(value);
the var value is local to the onclick function, so has to be accessed inside of that function or made global.
Once you have jQuery loaded on the page, it should be as easy as calling your helper function inside the click event.
$('#getTextBoxValue').on("click", function(){
loadPdf( $("#textbox1").val() );
});
You've tagged this as javascript but The code you are using to grab your values and bind your functions is jQuery. The error you are getting is telling you that there is no mapping of "$" to jQuery. If you want to make sure you have the reference set, you can replace the $ with the string "jQuery" so $('someselector') becomes jQuery('someselector').
BUT, this may just be the console you are using. You have another error which is probably the issue. You have this:
$('#getTextBoxValue').on("click", function(){
var value = $("#textbox1").val();
});
In this your value is locally scoped in the callback. Unless you do something with it before the function exits, you lose it completely. If you intend to do something with it later, you have to globally scope it by bringing it out of any function definition.
var value;
...
function someFunction(){
...
$('#getTextBoxValue').on("click", function(){
value = $("#textbox1").val();
});
}
The reason for this is due to scope.
You are defining your variables within the function with var.
$(document).ready(function() {
var value;
var pdf;
var value;
/* Then do your functions. This will make then global.
When you type then within your functions do not put var in front of them */
});
I have this function:
$(function ($) {
...
});
var getNotifyBar = $(".NotifyBar");
function showNotify(text) {
getNotifyBar.hide().find(".text").html(text).end().slideDown();
}
And when I use function showNotify(text) nothing happens. But when I put it in the JavaScript console (of the browser) it works.
More than likely this is running before all the elements with class NotifyBar are rendered
var getNotifyBar = $(".NotifyBar");
Which means that it is empty when you try to use it later. you should do this instead:
var getNotifyBar;
$(function ($) {
getNotifyBar = $(".NotifyBar");
});
Now it should be properly loaded. Next, you need to remember that getNotifyBar is a reference to a jQuery object already loaded from a selector. As such, you do not need to wrap it in $(). You should make this change:
function showNotify(text) {
getNotifyBar.hide().find(".text").html(text).end().slideDown();
}
Your code has no chance of working now and works from console, because when you run it in console it's after the DOMReady. Put the code in place of your 3 dots in the example and it will work, because:
$(function($){
//code here
})
will run the code after DOMReady