mpavlovic89
mpavlovic89

Reputation: 769

Generate input button with onClick function using JavaScript DOM

I use JavaScript to generate form input fields on my page. Everything works fine, except the button. I came across some problems generation the button's onClick function using DOM. You can see the code below, but on my page, there is no the onClick function as the attribute of the input button tag:

n = 1;
function generate() {
    var radiomore = document.createElement("input");
    radiomore.type = "button";
    radiomore.name = "opt[" + n + "]";
    radiomore.value = "Add more options";
    radiomore.setAttribute = ('onClick',addradiomore);
    var div = document.createElement("div");
    div.innerHTML = "Op: " + radiomore.outerHTML + "<br/>";
    document.getElementById("mydiv").appendChild(div);
n++;
}

function addradiomore() {
    //here goes the function code
}

And this is what it generates on my page:

<input type="button" name="opt[1]" value="Add more options">

There is no function?!?!

P.S. Even if I use like this it doesn't work:

radiomore.onclick = addradiomore();

Upvotes: 1

Views: 263

Answers (2)

Gaurang Tandon
Gaurang Tandon

Reputation: 6781

You should use this:

radiomore.onclick = addradiomore;

DEMO

Upvotes: 3

MasterScrat
MasterScrat

Reputation: 7386

What about:

radiomore.onclick = function () {
    addradiomore();
};

Upvotes: 2

Related Questions