Reputation: 65
I've been trying to make a simple script, but I got stuck. It should work like this:
User click the ADD button
to add field for creating question, after that, user can click ADD ONE OPTION button
, in order to create additional blank textareas below the question.
It's not working. Even I make an ADD button work, somehow, the other button stops, I got smth like Cannot call method 'appendChild' of null.
This is the code:
HTML:
<input type="submit" value="ADD" onclick="addquestion();" />
<br/><br/>
<div id="below"></div><br/>
JAVASCRIPT:
n=1;
function addquestion() {
var textarea = document.createElement("textarea");
textarea.name = "question[" + n + "]";
var addone = document.createElement("input");
addone.type = "button";
addone.value = "Add one option";
addone.onclick = "insertbelow("+n+")";
var div = document.createElement("div");
div.innerHTML = n + ". Question: <br />" + textarea.outerHTML + "<br />" + addone.outerHTML + "<br /><div id=\"radiodown"+n+"\" ></div><hr/><br/>";
document.getElementById("below").appendChild(div);
n++;
}
function insertbelow(index) {
var option = document.createElement("textarea");
option.name = "rad["+index+"]";
var optiondiv = document.createElement("div");
optiondiv.innerHTML = option.outerHTML + "<br/>";
document.getElementById("radiodown"+index).appendChild(optiondiv);
}
Upvotes: 1
Views: 4341
Reputation: 1875
Here is fiddle check out its working fine.
Updated: Javascript
n=1;
function addquestion() {
var textarea = document.createElement("textarea");
textarea.name = "question[" + n + "]";
var addone = document.createElement("input");
addone.type = "button";
addone.value = "Add one option";
addone.id="id_"+n;
var div = document.createElement("div");
div.innerHTML = n + ". Question: <br />" + textarea.outerHTML + "<br />" + addone.outerHTML + "<br /><div id=\"radiodown"+n+"\" ></div><hr/><br/>";
document.getElementById("below").appendChild(div);
var btn=document.getElementById("id_"+n);
if(btn.addEventListener){
btn.addEventListener('click', function() { insertbelow(this)});
} else if(btn.attachEvent){ // IE < 9 :(
btn.attachEvent('onclick', function() { insertbelow(this)});
}
n++;
}
function insertbelow(index) {
index=index.id.split("_")[1];
var option = document.createElement("textarea");
option.name = "rad["+index+"]";
var optiondiv = document.createElement("div");
optiondiv.innerHTML = option.outerHTML + "<br/>";
document.getElementById("radiodown"+index).appendChild(optiondiv);
}
Upvotes: 3
Reputation: 124
It looks like you're getting an error because your trying to target a div with the id 'radiodown,' but that doesn't appear to exist.
Upvotes: 0
Reputation: 1152
When trying to add the onclick event you don't really give the function as handler, but the result of the execution of the function (nothing in your case). This can solve your issue:
addone.onclick = function() { insertbelow(n) };
Upvotes: 2