I'm trying to do some validation for groups of radio buttons, where each group needs to have a value selected. I'm attempting to use Knockout-Validation to do the validation, but I'm having trouble making this dynamic. I can set up the validation, but getting it to validate each group individually is a challenge. Right now it's treating all groups of questions the same. I have an example on JSFiddle which shows the current situation.
I create the questions dynamically in the back end from a DB, but I could potentially add in a unique identifier for each question, but how do I reference an observable who's name I can't know ahead of time for a number of questions I can't predetermine the number of?
Example code form JSFiddle:
$(function() {
var viewModelQuestionnaire = ko.validatedObservable({
'checkScore': ko.observable().extend({
required: true
}),
submit: function () {
if (this.isValid()) {
alert('Thank you.');
} else {
console.log(this);
alert('Please check your submission.');
this.errors.showAllMessages();
}
}
});
ko.applyBindings(viewModelQuestionnaire);
});
<form action="/Questionnaire/Save" method="post"> <table id="ESAS-questions">
<tr class="esas-question-row">
<td class="esas-best-area">
<div class="esas-best-symptom">No Pain</div>
</td>
<td class="esas-score-area">
<span class="esas-score">0<input type="radio" name="question_id-1" value="0" data-bind="checked: checkScore"/></span>
<span class="esas-score">1<input type="radio" name="question_id-1" value="1" data-bind="checked: checkScore"/></span>
<span class="esas-score">2<input type="radio" name="question_id-1" value="2" data-bind="checked: checkScore"/></span></td>
<td class="esas-worst-area">
<span class="esas-worst-symptom">Worst Possible Pain</span>
</td>
</tr>
<tr class="esas-question-row">
<td class="esas-best-area">
<div class="esas-best-symptom">No Tiredness</div>
<div class="esas-best-subtext">(Tiredness = lack of energy)</div>
</td>
<td class="esas-score-area">
<span class="esas-score">0<input type="radio" name="question_id-2" value="0" data-bind="checked: checkScore"/></span>
<span class="esas-score">1<input type="radio" name="question_id-2" value="1" data-bind="checked: checkScore"/></span>
<span class="esas-score">2<input type="radio" name="question_id-2" value="2" data-bind="checked: checkScore"/></span> </td>
<td class="esas-worst-area">
<span class="esas-worst-symptom">Worst Possible Tiredness</span>
</td>
</tr>
</table>
<p><input type="submit" value="Submit" class="finish" data-bind="click:submit" /></p>