4

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?

0

1 Answer 1

13

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;

}
Sign up to request clarification or add additional context in comments.

3 Comments

Ok this works thanks a lot! I have the issue of still needing to pass information to the onchange though? How can I do this...
why not this: el.setAttribute('onChange', 'validation();');
@Milix that would also work, yes. I just prefer the other syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.