multiple functions onClick() not working - javascript

Below is the code that I used for multiple java scripts on a single button. But only any one is working when I disable the second one. Please let me know: how do I change my code to make it to work fine?
function invoke(but)
{
if(but==0)
{
function move(){
document.getElementById('tgt1').value =
document.getElementById('Allocation').value;
document.getElementById('Allocation').value="";
document.getElementById("Send").disabled=true;
}document.myform.action="Alloc_Insert.do";
}
else if(but==1)
{
document.myform.action="";
}
else if(but==2){ document.myform.action="WL_Verif.do";}
else if(but==3){ document.myform.action="Add_Query.do";}
document.myform.submit();
}
And the html is as below:
<input type="Submit" value="Allocate" id="Send" name="submit" onClick="invoke(0);move();"/><br/>

change the name of the button to something else than "submit"
To explain what happens:
When you assign the name-attribute "submit" to the button(or any other form-element), this element will be accessible via
document.myform.submit
but there is also the build-in method of a form: submit(), you also may access it by using
document.myform.submit
What happens now when you call document.myform.submit()
I'll write the code a little bit different, and you will see trouble:
document.myform['submit']()
Instead of accessing the built-in method, the code points first to the form-element, and then tries to execute the method. But a form-element is not a method, it all ends up in an error and the rest of the script(including the call of move() ) will not get executed.
It's the same with "reset", you never should use the name of a built-in property/method of the form-element as name for form-elements.

notice the 'move' function is not declared outside the 'invoke' function.
Then;
either wrap them in a self invoking function:
onclick="(function(){ invoke(0);move(); })();"
or attach event handlers (preferred usually)
div.attachEventListener('click', function () { ... }); // DOM 3
div.attachEvent('click', function () { ... }); // IE

Your functions are declared in a weird way. You're defining move inside of invoke, which I don't think you want. If you want to have two functions, put move outside of invoke, like this:
function move(){
document.getElementById('tgt1').value =
document.getElementById('Allocation').value;
document.getElementById('Allocation').value="";
document.getElementById("Send").disabled=true;
}
function invoke(but)
{
if(but==0)
{
move();
document.myform.action="Alloc_Insert.do";
}
else if(but==1)
{
document.myform.action="";
}
else if(but==2){ document.myform.action="WL_Verif.do";}
else if(but==3){ document.myform.action="Add_Query.do";}
document.myform.submit();
}
A note: it's generally not a good idea to use onClick in your HTML -- it's better to put that in your JavaScript.

I think the problem is the scope of the move() function. Try defining move outside of invoke.
function invoke (but) {
if(but==0) {
document.myform.action="Alloc_Insert.do";
// I don't know if you meant to call move() here or not
}
else if (but==2) { document.myform.action="WL_Verif.do"; }
else if (but==3) { document.myform.action="Add_Query.do"; }
document.myform.submit();
}
function move(){
document.getElementById('tgt1').value =
document.getElementById('Allocation').value;
document.getElementById('Allocation').value="";
document.getElementById("Send").disabled=true;
}
Also, properly formatting your code will do wonders to the legibility of it.
NOTE: Firefox seems to be quite happy to execute the onClick="invoke(0);move();" even if move is defined inside invoke. Chrome however won't execute move because it can't find it. So be sure to test your script in multiple browsers as well.

Related

How does prototype work for onSubmit:function()?

I was working on Co-drops Minimal Form Interface. I couldn't understand this code snippet in stepsForm.js. (Line 50)
stepsForm.prototype.options = {
onSubmit : function() { return true; }
};
I am new to JS, and wouldn't mind an explanation of the entire code in stepsForm if anyone has the time to do so. But, for the time being, an explanation for the above can do wonders for me. I know what a prototype is, but the onSubmit part is going over my head. I read on another question that this is to prevent refresh, but I feel that is wrong.
The library exposes options property that you may/can use to pass your own overriding values.This one in particular, exposes onSubmit.
For any html form an onSubmit is called when the submit action is invoked by another function or by click.
In the library the default onSubmit is returning true, meaning just execute the action. This can be overriden with you custom function like this...
<script>
var FORM_ELEMENT = document.getElementById( 'myForm' )
new stepsForm(FORM_ELEMENT, {
onSubmit :
function (FORM_ELEMENT) {
alert('You are about to submit the form ');
//manipulate your form or do any preprocess work...
return true;
});
</script>
Within the library the _submit (line 196 stepForm.js) is called which inturn calls the onSubmit. This time, instead of the default, it will execute the one we added above.
stepsForm.prototype._submit = function() {
this.options.onSubmit(this.el);
}
Hope that helps.

How do I use a function as a variable in JavaScript?

I want to be able to put the code in one place and call it from several different events.
Currently I have a selector and an event:
$("input[type='checkbox']").on('click', function () {
// code works here //
});
I use the same code elsewhere in the file, however using a different selector.
$(".product_table").on('change', '.edit_quantity', function () {
// code works here //
});
I have tried following the advice given elsewhere on StackOverflow, to simply give my function a name and then call the named function but that is not working for me. The code simply does not run.
$(".product_table").on('change', '.edit_quantity', function () {
calculateTotals() {
// code does not work //
}
});
So, I tried putting the code into it's own function separate from the event and call it inside the event, and that is not working for me as well.
calculateTotals() {
// code does not work //
}
So what am I doing wrong ?
You could pass your function as a variable.
You want to add listeners for events after the DOM has loaded, JQuery helps with $(document).ready(fn); (ref).
To fix your code:
$(document).ready(function() {
$("input[type='checkbox']").on('click', calculateTotalsEvent)
$(".product_table").on('change', '.edit_quantity', calculateTotalsEvent)
});
function calculateTotalsEvent(evt) {
//do something
alert('fired');
}
Update:
Vince asked:
This worked for me - thank you, however one question: you say, "pass your function as a variable" ... I don't see where you are doing this. Can you explain ? tks. – Vince
Response:
In JavaScript you can assign functions to variables.
You probably do this all the time when doing:
function hello() {
//
}
You define window.hello.
You are adding to Global Namespace.
JavaScript window object
This generally leads to ambiguous JavaScript architecture/spaghetti code.
I organise with a Namespace Structure.
A small example of this would be:
app.js
var app = {
controllers: {}
};
You are defining window.app (just a json object) with a key of controllers with a value of an object.
something-ctlr.js
app.controllers.somethingCtlr.eventName = function(evt) {
//evt.preventDefault?
//check origin of evt? switch? throw if no evt? test using instanceof?
alert('hi');
}
You are defining a new key on the previously defined app.controllers.somethingCtlrcalled eventName.
You can invoke the function with ();.
app.controllers.somethingCtlr.eventName();
This will go to the key in the object, and then invoke it.
You can pass the function as a variable like so.
anotherFunction(app.controllers.somethingCtlr.eventName);
You can then invoke it in the function like so
function anotherFunction(someFn) { someFn();}
The javascript files would be structured like so:
+-html
+-stylesheets
+-javascript-+
+-app-+
+-app.js
+-controllers-+
+-something-ctlr.js
Invoke via chrome developer tools with:
app.controllers.somethingCtlr.eventName();
You can pass it as a variable like so:
$(document).ready(function() {
$('button').click(app.controllers.somethingCtlr.eventName);
});
JQuery (ref).
I hope this helps,
Rhys
It looks like you were on the right track but had some incorrect syntax. No need for { } when calling a function. This code should behave properly once you add code inside of the calculateTotals function.
$(".product_table").on('change', '.edit_quantity', function () {
calculateTotals();
});
$("input[type='checkbox']").on('click',function() {
calculateTotals();
});
function calculateTotals() {
//your code...
}
You could just condense it all into a single function. The onchange event works for both the check box and the text input (no need for a click handler). And jQuery allows you to add multiple selectors.
$('input[type=checkbox], .product_table .edit_quantity').on('change', function() {
console.log('do some calculation...');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="product_table">
<input type="checkbox">
<input class="edit_quantity">
</div>

Problems calling a function inside a listener (onClick)

I've looked around on here for an answer to this but I can't find anything that works.
Basically I'm making a tower defence game. Each tower is dynamically created and is onClick enabled. Inside the onClick listener I am trying to call a method within the class.
e.g a player clicks the tower and can choose upgrades
However the method within the listener is outputing undefined function. I know this is clearly something to do with my scope. But I can't figure out what I'm missing?
Surely it should be something like:
someListener: function(){
this.game.doSomeOtherFunction();
}
I've tried a console.log and someListener is definitely being called, but the method inside is undefined.
Thanks,
Its not working because this changes context accordingly within a callback. You can do something like this:
var self = this;
...
someListener: function(){
self.game.doSomeOtherFunction();
}
...
Or simply you could also do this:
someListener: (function () {
var callback = function(){
this.game.doSomeOtherFunction();
}
return callback.bind(this);
}())
I hope it helps.

Why does "this.myFunction" not work when calling a function inside an object?

Here are two samples of code. The first one does not work and the second one does, though I'm completely at a loss as to why. Can someone explain this?
[I'm writing a simple game using a bit of jQuery to be played in a webkit browser (packaged with Titanium later).]
In the first example, Firebug tells me that "this.checkCloud" is not a function.
function Cloud(){
this.checkCloud = function(){
alert('test');
}
$("#"+this.cloudName).click(function(){
this.checkCloud();
});
}
...but then this works:
function Cloud(){
this.checkCloud = function(){
alert('test');
}
var _this = this;
$("#"+this.cloudName).click(function(){
_this.checkCloud();
});
}
This one works perfect.
Why does the first one not work? Is it because "this.checkCloud" is inside of the anonymous function?
in this example:
$("#"+this.cloudName).click(function(){
this.checkCloud();
});
this referrers to the element selected(jquery object).
what you can do is use private functions
var checkCloud = function(){
alert('test');
}
this way you can simply call it inside your anonymous function
$("#"+this.cloudName).click(function(){
checkCloud();
});
That is because the meaning of this can potentially change each time you create a new scope via a function. The meaning of this depends on how the function is invoked (and the rules can be insanely complicated). As you discovered, the easy solution is to create a second variable to which you save this in the scope where this has the expected/desired value, and then reuse the variable rather than this to refer to the same object in new function scopes where this could be different.
Try this:
function Cloud(){
this.checkCloud = function(){
alert('test');
}
var func = this.checkCloud;
$("#" + this.cloudName).click(function(){
func();
});
}
When you assign an even listener to an element, jQuery makes sure that this will refer to the element. But when you create the _this variable, you're creating a closure that jQuery couldn't mess with, even if it wanted to.

Unable to re-define a function in my javascript object

I have an object defined using literal notation as follows (example code used). This is in an external script file.
if (RF == null) var RF = {};
RF.Example= {
onDoSomething: function () { alert('Original Definition');} ,
method1 : function(){ RF.Example.onDoSomething(); }
}
In my .aspx page I have the following ..
$(document).ready(function () {
RF.Example.onDoSomething = function(){ alert('New Definition'); };
RF.Example.method1();
});
When the page loads the document.ready is called but the alert('Original Definition'); is only ever shown. Can someone point me in the right direction. I basically want to redefine the onDoSomething function. Thanks, Ben.
Edit
Thanks for the comments, I can see that is working. Would it matter that method1 is actually calling another method that takes the onDoSomething() function as a callback parameter? e.g.
method1 : function(){
RF.Example2.callbackFunction(function() {RF.Example.onDoSomething();});
}
Your code as quoted should work (and does: http://jsbin.com/uguva4), so something other than what's in your question is causing this behavior. For instance, if you're using any kind of JavaScript compiler (like Closure) or minifier or something, the names may be being changed, which case you're adding a new onDoSomething when the old one has been renamed. Alternately, perhaps the alert is being triggered by something else, not what you think is triggering it. Or something else may have grabbed a reference to the old onDoSomething (elsewhere in the external script, perhaps) and be using it directly, like this: http://jsbin.com/uguva4/2.
Thanks for the response .. in the end the answer was unrelated to the code posted. Cheers for verifying I wasn't going bonkers.

Categories