Reputation: 9859
I have got JSON file that I iterate.
It have next structure:
{
"id": 4, "question": "Select one color", "answers":
[
{"id": 1, "answer" : "Green", "isSelected" : false},
{"id": 2, "answer": "Red", "isSelected" : false},
{"id": 3, "answer": "Blue", "isSelected" : false},
{"id": 3, "answer": "White", "isSelected" : false}
],
"MaxAllowedChoice" : 2
}
I need to enable/disable all other items (checkboxs) if MaxAllowedChoice
is reached.
I am iterate it's with next code:
processOneQuestion: function (question)
{
var isSelectedCount = 0;
for(var answer of question.answers) // just calculation
{
if(answer.isSelected)
{
isSelectedCount++;
}
console.log("isSelectedCount --> ", isSelectedCount);
}
for(var answer of question.answers) // Enabling/Disabling
{
if(isSelectedCount >= question.MaxAllowedChoice)
{
console.log("isSelectedCount : " + isSelectedCount + " | question.MaxAllowedChoice: " + question.MaxAllowedChoice);
if(!answer.isSelected) // disable unselected
{
answer.isDisabled = true;
console.log("answer.isDisabled = true");
}
}
if(isSelectedCount !== question.MaxAllowedChoice ) // if MaxAllowedChoice less then isSelectedCount set iterated iterated answers isDisabled to false
{
if(!answer.isSelected) // disable unselected
{
answer.isDisabled = false;
console.log("I hope that answer.isDisabled = false was added")
}
}
}
}
HTML code:
<div v-for="firstLevelAnswer in question.answers">
<label v-if="!question.isRadioButton"><span class="firstLevelAnswer"><input type="checkbox" class="big-checkbox" :disabled="firstLevelAnswer.isDisabled" v-model="firstLevelAnswer.isSelected" />{{firstLevelAnswer.answer}}</span></label>
<label v-if="question.isRadioButton"><span class="firstLevelAnswer"><input type="radio" class="big-checkbox" name="myvalue"/>{{firstLevelAnswer.answer}}</span></label>
<span v-if="firstLevelAnswer.isTextInput"><input type="text"/></span>
| firstLevelAnswer.isSelected: {{firstLevelAnswer.isSelected}}
+>| <span>{{firstLevelAnswer.isDisabled}}</span>
All work only if I add to JSON key: "isDisabled" : false
like:
{"id": 3, "answer": "White", "isSelected" : false, "isDisabled" : false}
But I want add "isDisabled" : false
property in JS dinamicaly.
But I can't understand what I am doing wrong and why items are not disabling. http://img.ctrlv.in/img/16/03/12/56e47dd115d82.png
It's look like property are added, but does not affect
I have got filling that because on start this property is not exists latter adding of it cause problem. Is it's possible?
Upvotes: 0
Views: 35
Reputation: 7303
I would follow this logic. Everytime I select an option, I would check if I reached the maximum allowed limit.
checkDisabled: function() {
var selectedCount = 0;
for (var i = 0; i <= this.question.answers.length; i++) {
if (this.question.answers[i].isSelected == true)
selectedCount++;
}
(selectedCount >= this.question.MaxAllowedChoice) ? return true : return false;
}
Then use this method in your HTML to disable or enable the field.
Upvotes: 1