I have an HTML page that contains questions and answers. I want to extract the data (questions/answers) from the HTML page and put it in a JavaScript object.
This is the class structure in my HTML page:
- question-block
- question (only 1 question per question block)
- answer (multiple answers possible per question)
This is my HTML code with the structure:
<div class="question-block">
<h3>Question 1</h3>
<label class="question">Name</label>
<input type="text" class="answer" />
<div class="question-block" style="margin-left:20px;">
<h4>Question 1 a</h4>
<label class="question">What is your gender?</label>
<div class="radio">
<input type="radio" class="answer" name="gender" id="radio-male" value="male">
<label for="radio-male">Male</label>
</div>
<div class="radio">
<input type="radio" class="answer" name="gender" id="radio-female" value="female">
<label for="radio-female">Female</label>
</div>
</div>
</div>
<div class="question-block">
<h3>Question 2</h3>
<label class="question">Occupation</label>
<input type="text" class="answer" />
</div>
<br />
<button id="extract" type="button">Extract HTML data</button>
<pre id="extract-div"></pre>
I want to create a object structure in JavaScript like this:
{
"questions": [
{
"question": "Name",
"answers": [
{
"answer": "Kristof"
}
]
},
{
"question": "What is your gender?",
"answers": [
{
"answer": "Male"
}
]
},
{
"question": "Occupation",
"answers": [
{
"answer": "Student"
}
]
}
]
}
Everything works, except for the nested "question-block" (1a. What is your gender?). The answer of this question is also added to question 1.
How can I select only the answers that are located in the current "question-block" class with JavaScript or JQlite (I'm using angular).
It should be possible to nest my "question-block" classes multiple levels deep. (not only 1 level like in the example)
If you want to test it or check out my JavaScript code, here is my fiddle: https://jsfiddle.net/aywxte23/
nameattribute values, you could use a JavaScript library I created called Reaper, which grabs all theinput,textareaandselectelements inside a given element and creates a JavaScript object using the form field name attributes as a guide to the object property names and data types.