views:

62

answers:

4

I wont to add multiple function onchange from javascript to the same input. some thik like this:

this.el = document.getElementById(this.docID);

if(x==y) {

this.el.onchange += function(){ // some code }

} if(a==b) {

this.el.onchange += function(){ // some code }

}

A: 

You can't add 2 functions together, that code is wrong. There's only 1 onchange function.

So you could do something like this:

this.el.onchange = function() {   
    if(x==y) {
        // some code
    } else if(a==b) {
        // some other code  
    }  
}
Luca Matteis
I can't do these, is a compliced bussines logic behind these code
I can call from html too function:<input type="text" id="txtID" onchange="fn1();fn2();"/>I wont to do these from javascript
+1  A: 

If you want to chain onchange functions, you can do something like this:

this.el = document.getElementById(this.docID);

if(x==y) {
  this.el.onchange = function(){ // some code }
}

if(a==b) {
  var oldOnChange = this.el.onchange;
  this.el.onchange = function(){ 
    // execute previous onchange function
    if(oldOnChange) oldOnChange();

    // some code 
  }
}

Like this you can also decide, whether you want the old onchange function to be executed before or after the new onchange code.

inflagranti
A: 

Instead of using the onchange attribute, you should think about using addEventListener and the other DOM2 methods. There are some cross-browser issues which crop up (even when using the onchange attribute) so my recommendation is to use a library, such as the jQuery change event observer.

Using jQuery, your code example would look like this:

this.el = document.getElementById(this.docID);

if(x==y) {
    $(this.el).change(function() { /* some code */ });
}
if(a==b) {
    $(this.el).change(function() { /* some code */ });
}
Douglas
i can't use jquery because of $() function name conflict
Try http://api.jquery.com/jQuery.noConflict/
Douglas
A: 

this.el.onchange calls a main function after this calling you do comparison and calls other function

this.el = document.getElementById(this.docID);

this.el.onchange += functionx();

functionx() {

if(x==y) {

this.el.onchange += functionY(){ // some code }

} if(a==b) {

this.el.onchange += functionZ(){ // some code }
}

}

Judas Imam
onchange becomes a function, it's not a string anymore at this point. So it won't support concatenation.
Fabien Ménager