createElement in javascript to set "onchange" attribute

html, javascript

Solution

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;

}

Problem

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?

Original source