I am trying to access a dynamically generated DIV using document.getElementById but getting cannot set property innerHTML of null and that's pretty obvious.
Basically I am trying to build a type of interactive form just like https://www.typeform.com/
I want to create seperated DIV's for each question.
Here is what I have done so far:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Interactive Forms</title>
<script src="script.js"></script>
</head>
<body>
<center>
<div id="playArea">
<h3>Hello Stranger! Let's start</h3> <br/>
<button id="start" onclick="Questions()">Let's start</button><span>or Hit Enter</span>
</div>
</center>
</body>
</html>
script.js
var questions = [
"Hey, what's you name?",
"Can I know your E-mail ID please?",
"Would you also like to subscribe to the newsletter?"
];
var html = "";
var i =0;
addEventListener("keydown", function(event){
if(event.keyCode==13){
Question();
}
if(event.code==39){
nextQuestion();
}
});
function Question(){
html = questions[0]+"<br>"+"<input type='text' class='answer'><button onclick='nextQuestion()'>Ok</button><span>or Hit Right Arrow</span><br>";
document.body.innerHTML = html;
// document.getElementById("playArea").innerHTML = html;
i++;
}
function nextQuestion(){
if(i<questions.length){
var html2 = "";
newDiv = document.createElement("div");
check="'answer"+i+"'";
console.log("'answer"+i+"'");
newDiv.setAttribute("id", "'answer"+i+"'");
console.log(newDiv.id);
html2 = questions[i]+"<br><input type='text' id='answer'><button onclick='nextQuestion()'>Ok</button><span>or Hit Right Arrow</span><br>";
newDiv.innerHTML = html2;
oQ = document.getElementById("otherQuestions");
document.body.insertBefore(newDiv, oQ);
i++;
}
else{
document.body.innerHTML = "Thank you for the response";
}
}