javascript onclick not firing on button click - javascript

I am trying to call a JS function when the user clicks a button. But the onclick event is not being fired. The developer tools shows me the following error:
Error executing:
function (/*Event*/ e){
// summary:
// Handler when the user activates the button portion.
if(this._onClick(e) === false){ // returning nothing is same as true
e.preventDefault(); // needed for checkbox
}else if(this.type == "submit" && !this.focusNode.form){ // see if a nonform widget needs to be signalled
for(var node=this.domNode; node.parentNode/*#5935*/; node=node.parentNode){
var widget=dijit.byNode(node);
if(widget && typeof widget._onSubmit == "function"){
widget._onSubmit(e);
break;
}
}
}
}
ReferenceError
arguments: Array[1]
get message: function () { [native code] }
get stack: function () { [native code] }
set message: function () { [native code] }
set stack: function () { [native code] }
type: "not_defined"
__proto__: Error
Here is my code:
HTML
<td>
<button dojoType = "xwt.widget.form.TextButton" id = "pingButton" baseClass = "defaultButton" onclick = "onPing();">Ping
</button>
</td>
JS:
onPing : function() {
alert('works');
}
Any suggestions on what to do?

In lieu of continuing a rather bang-head-against-table thread, I will explain to both the OP and others why he is having problems.
Problem 1: The OP did not post all relevant code. The OP is apparently new to both OOP and SO and he made the fatal error of assuming less is more. We can see that there is an onPing function which is part of an object as per the colon : syntax. If he were to post all of his code, his javascript would look something like this:
var myObject = {
onPing: function() {
alert("works");
}
};
It should be noted here that I am not sure what the name of his object is. I used the name myObject so as to imply "your object name here".
Problem 2: There is an onclick function which is defined inline with a button. This is not good practice and can lead to bugs... especially when so many cut-and-paste javascript snippets are written inside of closure:
(function() {
/*
This is an example of closure.
Any variables/objects/functions defined in here are not accessible to the outside world
*/
})();
Problem 3: The code appears to rely on an attribute type with a value submit. Therefore the button should have that attribute set:
<button type = "submit" dojoType = "xwt.widget.form.TextButton" id = "pingButton" baseClass = "defaultButton" onclick = "onPing();">Ping</button>
While a quick and dirty solution might be to declare a global function called onPing, this might cause problems with other libraries, makes the code more difficult to maintain, and is just plain ol' bad practice and should never be encouraged. So lets explore a better solution which will do the following:
Show complete working code
Define objects within closure
Bind events through code, not inline
Here goes...
<button type="submit" dojoType="xwt.widget.form.TextButton" id="pingButton" baseClass="defaultButton">Ping</button>
<script>
(function() {
var myObject = {
onPing: function() {
alert("works");
}
};
document.getElementById('pingButton').onclick = myObject.onPing;
}());
</script>
And to be super nice, we include a jsfiddle.

This works
function onPing() {
alert("this");
}
Can leave button as it is....
<button dojoType = "xwt.widget.form.TextButton" id = "pingButton" baseClass = "defaultButton" onclick = "onPing();">Ping</button>

Related

Define the order of execution of functions after event in javascript

Just, before reading, I have read about this thread: Order of execution of functions bound to an event in Javascript but its not helping. Actually,
I have an anonymous function, define like that:
<input type="button" name="blablabla" value="Send" onclick="javascript:blablabla">
So, this function is on a button, use to validate forms. As you can see, It's an anonymous function, and I don't have any access on this code. This function start when I click on it. Okay, I have understood that
But, this function is not totally full, and I want to add my own, with her own logic of check. So I want my checks first, and then call the anonymous function. Here is my code:
function check() {
console.log("debut de check");
var participant = document.getElementById("new_participant_name");
var participant1 = document.getElementById("new_participant2_name");
var participant2 = document.getElementById("new_participant3_name");
participant = participant.value;
participant1 = participant1.value;
participant2 = participant2.value;
var trois_participants = (participant2) ? true : false;
if (!participant1 || !participant)
{
console.log("pas de participant1 ou participant, sert à rien de gérer la suite");
//if the script come here, I want to stop processing, and don't want to call the anonymous function.
return ;
}
}
window.onload = function()
{
document.getElementById("InsertButton").addEventListener('click', function () {
check();
})};
So, I want to call my function (check) before the anonymous function, but, with the same event. I don't know if I am totally understable... thanks per avance
EDIT: Sorry guys, My code have a bug before, yes the code is inlined, I will try all of your solutions tomorrow, thanks guys
If (and only if) the existing handler is attached using an inline onclick="..." handler, you can obtain its value, and then overwrite it:
window.onload = function() {
var el = document.getElementById('InsertButton');
var old_click = el.onclick;
el.onclick = undefined;
el.addEventListener('click', function() {
check();
old_click(this);
});
}
Why not create your own handler??
Element.prototype.myEventListener=function(name,func){
this.addEventListener(name,function(){
if(!check()){return;}
func();
});
};
Now you can do:
document.body.myEventListener("click",function(){
alert("t");
});
Check will always be called before the registered handler.
Note, to block the call, check must return false:
function check(){
return false;//no custom eventlistener fires
return true;//all will fire
}
Use the useCapture flag so you can intercept the event while it's travelling down to the button.
At that point you can perform your check, and if it fails you can call stopPropagation on the event to prevent it from reaching the handlers that are attached to its bubbling phase.
Also, by nature, events are quite bad at managing the order of execution. In general they depend on the order of registration of the listeners.
// code over which you have no control and can't change
var btn = document.getElementById("greeter");
btn.addEventListener("click", function() {
console.log("hello");
})
// code you can add later
function check() {
return Math.random() > 0.5;
}
window.addEventListener("click", function(e) {
var greeter = document.getElementById("greeter");
if (e.target === greeter && !check()) {
e.stopPropagation();
}
}, true)
<button id="greeter">hello world</button>

Click function runs on load; Uncaught TypError for undefined function [duplicate]

This question already has answers here:
Why does click event handler fire immediately upon page load?
(4 answers)
Closed 8 years ago.
This is a simple script that should make your text change color if you click on it. However, when I load the page, the color changes automatically (bypassing the click event) and console gives this error "Uncaught TypeError: undefined is not a function" on the line
allP.addEventListener("click", this.changeSomething(), false);
My questions are:
1) How can I make this very simple script work?
2) Any other feedback on coding better moving forward? I really appreciate any teaching points.
Markup:
<P>Lorem</P>
<P>Lorem</P>
Javascript:
var colorChanger = {
init : function() {
this.clickEvent();
},
config : {
myColor: "red"
},
clickEvent : function() {
allP = document.querySelectorAll("p");
allP.addEventListener("click", this.changeSomething(), false);
},
changeSomething: function(myColor) {
myColor = this.config.myColor;
$("p").css({
color: myColor // I know changing CSS in JS is bad practice but this is just for the sake of the exercise
})
}
}
$(document).ready(function() {
colorChanger.init();
});
Any feedback is really appreciated!
1) addEventListener expects a function as second argument but you're passing what the function returns (that is undefined).
2) In this.changeSomething, the context (this) is window, because that's the context of functions called on events.
Change
allP.addEventListener("click", this.changeSomething(), false);
to
allP.addEventListener("click", this.changeSomething.bind(this), false);
EDIT:
Also, this...
allP = document.querySelectorAll("p");
allP.addEventListener("click", this.changeSomething(), false);
..won't work. You can't just access the items in the nodeList like that.
Try something like this:
allP = document.querySelectorAll("p");
for (var i=0; i<allP.length; i++) {
allP.item(i).addEventListener("click", this.changeSomething.bind(this), false);
}

Can not prevent form submit when I add one line

I am stacked. My code can not prevent defaut action of submit. This was working fine until I add this.doSomething();.
Why this happens? Do I have to use preventDefault?
working code: http://jsfiddle.net/WwW5R/
HTML:
<div id="container">
<form action="" method="post" id="input">
<input type="submit">
</form>
</div>
JavaScript:
$(function() {
var ReserveUI = function($el) {
this.$form = {
input: $el.find('#input')
};
this._eventify();
};
ReserveUI.prototype.doSomething = function() {
return false;
}
ReserveUI.prototype._eventify = function() {
this.$form.input.submit(function() {
this.doSomething(); //if comment out this line, it works
return false;
});
};
var UI = new ReserveUI($("#container"));
});
thanks for reading:)
In your submit callback function, this no longer refers to your object, but to the element itself.
It's therefore causing an exception because the element has no doSomething property, and your return false is skipped.
Instead, write this:
ReserveUI.prototype._eventify = function() {
var self = this;
this.$form.input.submit(function(e) {
e.preventDefault(); // cancels event even if subsequent lines fail
self.doSomething();
});
};
See http://jsfiddle.net/xgGGx/1/ for a working example showing that it's just the scope issue causing the bug.
This is what script debugging tools are for - the reported error should have made the fault reasonably obvious...
This is a scope mismatch.
this.$form.input.submit(function() { //here "this" is ReserveUI
this.doSomething(); //here "this" is input button
return false;
});
And since there is no doSomething() on input button, the script breaks thus no longer executing the portion to return false.
Here is a way you can get around this
ReserveUI.prototype._eventify = function() {
var $this = this; //create a reference to the object
this.$form.input.submit(function() {
$this.doSomething(); //Now call the object method
return false;
});
};
Demo
Sounds like there's an error in your doSomething code (which I assume isn't just return false in your program).
To ensure the event does not continue, even if there's an error, do not return false but use e.preventDefault() instead:
this.$form.input.submit(function(e) {
e.preventDefault();
this.doSomething();
});

Transform any JavaScript function into a page event

I need to be able to achieve the following (one way or another):
function ShowContent() {}
document.onShowContent = function ()
{
// anything I want to happen....
}
What I'm trying to do is to add a kind of listener to me Advertisement code on the page that will auto refresh the ad slot when a specific function is called. Instead of having that function "ShowContent()" directly refresh the ad code, I want the ad code to refresh if it detects that "ShowContent()" has been called.
Thanks.
Modern javascript libraries make this easy. You can do it "by hand" of course, but here's a quick example with jQuery
First, the listener
$(document).bind( 'ShowContent', function()
{
// anything you want
});
Then the trigger
$(document).trigger( 'ShowContent' );
You could even go this route if you want
function ShowContent()
{
$(document).trigger( 'ShowContent' );
}
Here is a quick sample i threw together
var ev = (function(){
var events = {};
return {
on: function(name, handler){
var listeners = (name in events) ? events[name] : (events[name] = []);
listeners.push(handler);
},
raise: function(name){
var listeners = events[name];
if (listeners) {
var i = listeners.length;
while (i--) {
listeners[i]();
}
}
}
};
})();
// add a listener
ev.on("foo", function(){
alert("bar");
});
If you cannot manually alter the method in question to trigger the event, then you can 'wrap' it.
function methodIHaveNoControlOver(){
....
}
// intercept the call
var originalFn = methodIHaveNoControlOver;
// here we replace the FunctionDeclaration with a FunctionExpression containing a reference to the original FunctionDeclaration
methodIHaveNoControlOver = function(){
originalFn();
ev.raise("foo");
};
But note that this will not work if methodIHaveNoControlOver uses this to reference anything; so that will require more work.

How can I pass arguments to anonymous functions in JavaScript?

I'm trying to figure out how to pass arguments to an anonymous function in JavaScript.
Check out this sample code and I think you will see what I mean:
<input type="button" value="Click me" id="myButton" />
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
myButton.onclick = function(myMessage) { alert(myMessage); };
</script>
When clicking the button the message: it's working should appear. However the myMessage variable inside the anonymous function is null.
jQuery uses a lot of anonymous functions, what is the best way to pass that argument?
Your specific case can simply be corrected to be working:
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
myButton.onclick = function() { alert(myMessage); };
</script>
This example will work because the anonymous function created and assigned as a handler to element will have access to variables defined in the context where it was created.
For the record, a handler (that you assign through setting onxxx property) expects single argument to take that is event object being passed by the DOM, and you cannot force passing other argument in there
What you've done doesn't work because you're binding an event to a function. As such, it's the event which defines the parameters that will be called when the event is raised (i.e. JavaScript doesn't know about your parameter in the function you've bound to onclick so can't pass anything into it).
You could do this however:
<input type="button" value="Click me" id="myButton"/>
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
var myDelegate = function(message) {
alert(message);
}
myButton.onclick = function() {
myDelegate(myMessage);
};
</script>
The following is a method for using closures to address the issue to which you refer. It also takes into account the fact that may which to change the message over time without affecting the binding. And it uses jQuery to be succinct.
var msg = (function(message){
var _message = message;
return {
say:function(){alert(_message)},
change:function(message){_message = message}
};
})("My Message");
$("#myButton").click(msg.say);
By removing the parameter from the anonymous function will be available in the body.
myButton.onclick = function() { alert(myMessage); };
For more info search for 'javascript closures'
Event handlers expect one parameter which is the event that was fired. You happen to be renaming that to 'myMessage' and therefore you are alerting the event object rather than your message.
A closure can allow you to reference the variable you have defined outside the function however if you are using Jquery you may want to look at its event specific API e.g.
http://docs.jquery.com/Events/bind#typedatafn
This has an option for passing in your own data.
<input type="button" value="Click me" id="myButton" />
<script type="text/javascript">
var myButton = document.getElementById("myButton");
myButton.myMessage = "it's working";
myButton.onclick = function() { alert(this.myMessage); };
</script>
This works in my test suite which includes everything from IE6+. The anonymous function is aware of the object which it belongs to therefore you can pass data with the object that's calling it ( in this case myButton ).
The delegates:
function displayMessage(message, f)
{
f(message); // execute function "f" with variable "message"
}
function alerter(message)
{
alert(message);
}
function writer(message)
{
document.write(message);
}
Running the displayMessage function:
function runDelegate()
{
displayMessage("Hello World!", alerter); // alert message
displayMessage("Hello World!", writer); // write message to DOM
}
Example:
<input type="button" value="Click me" id="myButton">
<script>
var myButton = document.getElementById("myButton");
var test = "zipzambam";
myButton.onclick = function(eventObject) {
if (!eventObject) {
eventObject = window.event;
}
if (!eventObject.target) {
eventObject.target = eventObject.srcElement;
}
alert(eventObject.target);
alert(test);
};
(function(myMessage) {
alert(myMessage);
})("Hello");
</script>
What you have done is created a new anonymous function that takes a single parameter which then gets assigned to the local variable myMessage inside the function. Since no arguments are actually passed, and arguments which aren't passed a value become null, your function just does alert(null).
If you write it like
myButton.onclick = function() { alert(myMessage); };
It will work, but I don't know if that answers your questions.

Categories