Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

createElement in javascript to set "onchange" attribute

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?

like image 558
user1647308 Avatar asked Oct 17 '25 06:10

user1647308


1 Answers

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;

}
like image 190
scott.korin Avatar answered Oct 19 '25 20:10

scott.korin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!