Reputation: 101
I am creating a form from javascript. I have to put the onclick on the a tag to call a method when clicked. I am doing like this, but it is not appearing the onclick.
function remPass() {
var log = document.getElementById("login");
var form = document.createElement('form');
form.method = "post";
form.action = "";
log.appendChild(form);
var input = document.createElement('input');
input.type = "text";
input.name = "username";
input.className = "username";
input.placeholder = "Usuario";
var a = document.createElement('a');
a.className = "bt-enter pink";
a.id = "recordar";
a.href = "#";
a.onclick = "remember()"; //Here is the problem
a.innerHTML = "Recordar contraseña";
form.appendChild(input);
form.appendChild(a);
}
Upvotes: 1
Views: 229
Reputation: 4730
You should use setAttribute
method to set attributes / properties for the tag while creating it:
var a = document.createElement('a');
a.setAttribute("class", "bt-enter pink");
a.setAttribute("id", "recordar");
a.setAttribute("href", "#");
a.setAttribute("onclick ", "remember();");
a.innerHTML = "Recordar contraseña";
This is the most competent method of creating elements cross-browser.
Upvotes: 1
Reputation: 2447
You should give something of type function not a string:
a.onclick = remember;
//....
var remember = function() {
// remember logic
}
Upvotes: 0
Reputation: 2185
the right way is
a.onclick = remember; //without double quotes
var remember = function(){
//more code here...
};
Upvotes: 2
Reputation: 3383
You need use method, not method's result nor a string
a.onclick = remember;
And don't forget to create
function remember(){
//some code
}
Upvotes: 5
Reputation: 331
the correct way of doing is like that
a.onclick = remember; //do like that
var remember = function(){
//remember logic..
};
Upvotes: 4