Javascript add function call with parameters to button - javascript

I would like to add a function call including parameters to a HTML button via javascript. I know there are plenty of questions to this subject but none of the answers i found did work for me.
Note: My HTML and JS are in separate files which are correctly linked (the JS code works)
Problem:
I can add the function call like this:
var $add = $("#add");
$add.click(myFunction);
However $add.click(myFunction(i)); does not work.(Did also try with specific integer)
I have also tried it the following way:
document.getElementById('add').onclick = function() {myFunction(i);};
But like that the function does not even get applied to the button.
My function is defined in the JS file like this:
function myFunction(length) {
//do stuff with length I would notice
}

You can use some thing like function bind or do it using handler:
$add.click(function(e){
myFunction(i);
});

Related

Calling a function in a typescript file from HTML.

I'm new to HTML and Angular 2. I'm currently trying to figure out how to call a function that's inside a Typescript file from an HTML file.
Stripped down, the Typescript file (home.ts) function looks like this:
getConfigurations(sensorName: string) {
console.log('Home:getConfigurations entered...');
return 'sensor1';
}
In my HTML file (home.html), I would like to call 'getConfigurations' with a string parameter (right now 'getConfigurations()' returns 'sensor1' since I'm still testing things out). So, in HTML, how do I go about calling my getConfigurations method with a parameter (for simplicity - how can I call the method inside a simple div panel)? (I already have the value I want to pass in a variable called 'selectedSensor').
There is feature provided by angular is events binding by using you are able to call function whihc is exist in your ts file
also you can use interpolation syntax of angular to call function like this : -
<button (click)='getConfigurations("parameter")'>Button Click</button>
or something like this
{{getConfigurations('parameter')}}
for more info related to event binding in angular2 see here
working example Working Plunker

Javascript / jQuery basic function issue

I am trying to display a div on click. The function that is supposed to make the magic happen is:
$(document).ready(function showGogoasa() {
$('.gogoasa-newsletter').show();
});
Unfortunately, it does nothing. Which makes me scratch my head for hours as I have done small things like this in the past and they worked. I am trying to make this modification on the website of a client.
When I check the firebug console it says the following: ReferenceError: showGogoasa is not defined
I tried looking on Google for this kind of error but the similar cases had this kind of issue for not declaring a variable. Well, I do not have any variables.
I am trying to display a div on click.
Your code is running the function on a ready event and doesn't give the error you describe.
Presumably (it would have helped if you had provided a complete test case) you are also trying to bind the function as a click handler, but you can't do that because you have defined it using a function expression and not a function declaration (so it doesn't create a variable called showGogoasa outside of its own scope).
Define the function separately, then assign call it and bind it as a click event handler on the ready event.
$(document).ready(function ready_handler() {
function showGogoasa() { // Define it as a variable in the current scope
$('.gogoasa-newsletter').show();
}
showGogoasa(); // call it now
$("button").on("click", showGogoasa); // call it then
});
Well, I do not have any variables.
That's the problem :)
Functions are first class objects and when you say showGogoasa() that means "Get the value of showGogoasa and call it as a function".
Using jsfiddle or providing more code would have been helpful.
One issue is that you are missing the click event handler. For example when the user clicks on X then Y should happen/show. The following simple example may help you to see how it works:
http://jsfiddle.net/fionaredmond/1vbagj12/
$(document).ready(function(){
$("#showGogoasa").click(function(){
$(".gogoasa-newsletter").show();
});
});
$(document).ready(function() {
$('#idOfYourClickerElement').on('click', function(){
$('.gogoasa-newsletter').show();
});
});

extend a javascript option to add functionality

I need to call "MyOtherFunction" when "MyFunction"(which creates an element) completes, without MyFunction knowing what MyOtherFunction is.
The reason I need this is for extension of a jquery powered fileupload User Control that is used in several places with different functionality. A specific page shows a header and file count for it, and when the upload completes, I need to modify the file count according to how many files are displayed(by created elements) I thought :
$(UserControl).on(MyFunction, UploadElem, MyOtherFunction);
but this route is not accomplishing anything. The most I can alter the User Control is add in a function call, but without effecting the original user control functionality.
I'm not sure if because MyFunction isn't an event and doesn't bubble up or if it just isn't possible to use a defined function as a parameter of .on() is the reason I cannot get this code to work. Any suggestions?
Easiest way I can think of, is duck punching respectively hooking that method:
var _oldMyFunction = MyFunction;
MyFunction = function() {
_oldMyFunction.apply( this, arguments );
MyOtherFunction();
};
I managed to solve my own issue, but the context is important for the answer:
// Using a Global JavaScript object I created:
GlobalNameSpace.ExtensionFunction = function(oParam1, oParam2, oParam3)
{
/// <summary>All parameters are optional</summary>
return; // For instances when it is not being overwritten, simply return
}
//In the Code for the user control:
GlobalNameSpace.UploadControl.UploadComplete(oSender, oArgs)
{
///<summary>Handles the Upload process</summary>
// process the upload
GlobalNameSpace.ExtensionFunction(oSender, oArgs);
}
//and finally in the code to extend the functionality
GlobalNameSpace.Page.Init
{
///<summary>Initializes the page</summary>
// redefine the extension function
GlobalNameSpace.ExtensionFunction = function(oSender, oArgs)
{
GlobalNameSpace.Page.Function(oSender, oArgs);
}
}
This allows me to extend anything I need it to without polluting my objects, and having something generic already existing to call on to make my changes. This solution solves my problem of needing a onCreate function for the elements I create to represent my uploaded items to trigger the header displaying the number of files. Very useful

I have function but in firebug console it says its not a function where I am calling it?

I am using a function in two sites but when I want to implement it to third site it does not work. When I look into firebug console it says its not a function. My function is in a separate file called profilter.js look like this:
jQuery.fn.sfProductFilter = function (options) {
options = options || {};
return this.each(function () {
var pf = new SFProductFilter(this, options)
})
}
and I am calling it from a page and code is:
$(document).ready(function(){
console.log($("ul.productSmall"));
$('ul.productSmall').sfProductFilter(); //says not a function.
});
I have checked through console.log followings
1- jQuery is included already
2- If I console.log from the js file it works but inside any code block it does not
3- ul.productSmall shows right results in console.log
I can provide link of site but just not providing it so moderator wont thinks its a spam.
I have struggled a lot please let me know where I am making mistake?
(Copied from comment above.)
You are including jQuery twice, the second load happens far below the inclusion of profilter.js and destroys your custom function.
Are you including the jquery ui script? Looks like .button() is called in
function myChecks(){
$("#checkboxcontainer input[type='checkbox']").button();
}
I have a hunch this will do the trick.

PHP function HTML output shows in browser but not the Javascript innerHTML

I have a PHP function that queries a MySQL database and outputs an html table. This works fine with following PHP code:
<?php
showTable();
?>
But if I use the javascript code:
form.onsubmit = function() {
document.getElementById("php_code").innerHTML="<?PHP showTable(); ?>";
};
the browser does not show the table. There seems to be a problem with the (innerHTML) html string. I noticed for example that a carriage return inside a MySQL parameter causes problem with the innerHTML, but not with the PHP-only code.
Is there a way to fix this?
(the reason I wish to use the javascript bit is to be able to have a form with two buttons with different PHP functions depending on the form buttons clicked).
Php runs on the server, it generates the html page, and returns it to the browser for rendering. Javascript runs in the browser -- which happens after the php has finished running. It is not possible to invoke a php function directly from within a javascript function.
In order to do what you're trying to do, you'll need to move your php code into its own PHP file, and use something like jQuery's load() function to invoke your php via a separate http request. Something like this:
form.onsubmit = function() {
jQuery("#php_code").load('show_table.php');
};
where "show_table.php" contained something like this:
<?php
/** remember to include the function showTable()
* here, so you can call it below.
*/
function showTable() {
/* your function source here */
}
showTable();
Hope this helps. You might also want to do some research on web applications in general -- specifically, read up on the roles that are played by PHP and Javascript respectively.
edit
If you understand the distinction I've outlined above, and your actual intention really is to have the php function run when the page is initially loaded, rather than waiting till the javascript function is called, then you can modify your code as follows:
form.onsubmit = function() {
document.getElementById("php_code").innerHTML="<?PHP echo(addcslashes(showTable(), "\0..\37\\'\"/\177..\377")); ?>";
};
In order to use this approach, you will also need to make your function showTable() return the string rather than printing it out directly. One way to accomplish this is with php's output buffering functions. Just take your existing showTable() function, and wrap it like this:
function showTable() {
ob_start();
/* existing showTable logic goes here */
return ob_get_clean();
}
You need to escape the output of showTable() properly if you want to do it in a variable like that.
However, I propose a different method for you. Include the HTML like this:
<script type="text/html" id="showTable">
<?php showTable(); ?>
</script>
<script type="text/javascript">
form.onsubmit = function() {
document.getElementById("php_code").innerHTML= document.getElementById('showTable').innerHTML;
};
</script>
Notice the use of type="text/html" in the previous script tag. This will cause the table not to be shown to the browser, but retrievable by javascript.
Good luck.
Two things:
Be sure that no characters come out of showTable() that would interfere with the JavaScript code (like quotes)
Convert new lines to break characters (nl2br()) in your showTable() function.

Categories