3

I am trying to dynamically add a new input feild with the "onchange" attribute:

    var f = document.getElementById("dN[" + fieldsd + "]"); // create/insert new
    el = document.createElement("input");
    el = f.appendChild(el);
    el.name = "dName[" + fieldsd + "]";
    el.id = "dName[" + fieldsd + "]";
    el.onchange =  "validation()";

I have also tried setAttribute both don't work for me. Is there a way to make this work or a work around?

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
user1647308
  • 41
  • 1
  • 1
  • 5

1 Answers1

11

In JavaScript, set the onchange property to be a pointer to a function, not an actual string:

var f = document.getElementById("dN[" + fieldsd + "]"); // create/insert new
el = document.createElement("input");
el = f.appendChild(el);
el.name = "dName[" + fieldsd + "]";
el.id = "dName[" + fieldsd + "]";
el.onchange =  validation;

(Where you have a function named validation)

If you need to pass parameters, set onchange to a function that calls the validation function:

el.onchange = function () {  
    validation(param1, param2, ...);
};

Or, if you want information from the input itself, you can use the this keyword within your validation function:

el.onchange = validation;

....

function validation() {
    // this is the "context" for the function.  In this case
    // the element that changed.
    var value = this.value;

}
scott.korin
  • 2,537
  • 2
  • 23
  • 36