Reputation: 944
I am creating a form for a survey which should ask for quesions out of a Json object. My code works so far, but I feel like I miss knowledge of some polymer or JS functions that would make it more beautiful. Screenshot:
Script:
var questions = [
{
"question": "What do you want for christmas?"
, "mode": "radio"
, "answers": ["Nintendo", "iPony", "You", "A tiny little Shotgun"]
}
];
console.log(questions);
function foo() {
var question = document.createElement('div');
question.className = 'question';
question.innerHTML = "Frage:" + questions[0].question;
console.log(question);
var surveyQuestions = document.getElementById("survey-questions");
surveyQuestions.appendChild(question);
var answers = document.createElement('div');
answers.className = "answers";
questions[0].answers.forEach(buildRadio);
surveyQuestions.appendChild(answers);
function buildRadio(item, index) {
var paperCheckbox = document.createElement('paper-checkbox');
var br = document.createElement('br');
paperCheckbox.setAttribute("name",item);
paperCheckbox.setAttribute("value",item);
paperCheckbox.getElementsByTagName('div')[1].innerHTML = item;
paperCheckbox.children[1].innerHTML = item;
answers.appendChild(paperCheckbox);
answers.appendChild(br);
}
}
Another small exmaple for my problem:
<div class="card"></div>
creates
<div class="card style-scope survey-app"></div>
But
var card = document.createElement('div');
card.className = "card";
only creates
<div class="card"></div>
What would be best practice?
Upvotes: 0
Views: 235
Reputation: 944
The solution is using dom-repeat
and it works great:
<template is="dom-repeat" items="{{questions}}">
<div class="card">
<div class="question">Frage {{index}}: {{item.question}}</div>
<template is="dom-if" if="{{_isCheckQuestion(item)}}">
<template is="dom-repeat" items="{{item.answers}}">
<paper-checkbox>{{item}}</paper-checkbox>
<br>
</template>
</template>
<template is="dom-if" if="{{_isRadioQuestion(item)}}">
<paper-radio-group>
<template is="dom-repeat" items="{{item.answers}}">
<paper-radio-button name="{{item}}">{{item}}</paper-radio-button>
<br>
</template>
</paper-radio-group>
</template>
</div>
</template>
But the dom-if
is a little bit tricky
<script>
Polymer({
is: 'survey-app'
, properties: {
prop1: {
type: String
, value: 'survey-app'
}
}
, ready: function () {
this.questions = [
{
"question": "What do you want for christmas?"
, "mode": "check"
, "answers": ["Nintendo", "iPony", "You", "A tiny little Shotgun"]
}
, {
"question": "Yes or no?"
, "mode": "radio"
, "answers": ["yes", "no"]
},
];
}
, _isCheckQuestion: function (question) {
return question.mode == 'check'
}
, _isRadioQuestion: function (question) {
return question.mode == 'radio'
}
});
</script>
Upvotes: 1