使用击倒的jquery模板里面的单选按钮列表

时间:2011-11-15 10:41:45

标签: knockout.js jquery-templates

我在jquery模板中使用knockout,我被困在模板中的某个位置。我先告诉你代码。 这是我的模板

 <script type="text/x-jquery-tmpl" id="questionTemplate">
        <div class="questions">
               <div data-bind="text: QuestionText" style="font-weight:bold;"></div>
               {{if QuestionType == "FreeForm" }}
                       <textarea rows="3" cols="50" data-bind="value: ResponseValue"></textarea>
                   {{/if}}

                   {{if QuestionType != "FreeForm" }}
                       <table>
                        {{each(i,option) Options}}
                        <tr>
                       <td>
                       <input type="radio" data-bind="attr:{name:QuestionId},click:function(){ResponseValue=option.Value;}" />${option.Value}</td><td>- ${option.ResponsePercent} %</td> 
                       </tr>
                        {{/each}}
                       </table>    
                   {{/if}} 
            </div>
    </script>

以下是我使用它的方式

<div data-bind="template:{name:'questionTemplate',foreach:questionResponses()}">

基本上它正在做的是,它是为每个问题响应循环并检查问题类型是否为FreeForm然后它创建一个textarea否则它选择questionResponse的对象数组属性“Options”并使用jquery {{each}}来显示每个选项作为单选按钮。 在提交时,我选择“ResponseValue”属性的值,如果是textarea然后我得到textarea值,否则我得到选择单选按钮的值。 这一切都很好。

这就是它在UI中的外观

1. Tell me about yourself
[A Text Area Since it is a FreeForm Question]

2. How much you will rate yourself in MVC3?
RadioButton1
RadioButton2
RadioButton3

3. Blah Blah Blah?
RadioButton1
RadioButton2
RadioButton3
RadioButton4
RadioButton5
RadioButton6


... so.. on.. 

目前我正在将“QuestionId”指定为单选按钮的名称,并考虑使它们在问题中互斥。 所以这里的第二个问题是所有3个单选按钮都会说name =“111-1111-1111”。 而第三个问题的所有6个单选按钮都会说名字=“222-2222-2222” 注 - QuestionId的类型为Guid

唯一和小问题困扰我的是,它不允许我更改我的选择,我的意思是如果我选择RadioButton1进行问题2然后它不允许我选择RadioButton2或3,每个问题也是如此。这发生在Firefox中。虽然IE 9甚至不允许选择页面中的任何单选按钮。

任何帮助都会很明显

提前致谢

1 个答案:

答案 0 :(得分:7)

最好的办法是使用checked绑定单选按钮。您的绑定看起来像:

<input type="radio" data-bind="attr:{name:QuestionId, value: option.Value }, checked: $data.ResponseValue" />${option.Value}</td>
  • name属性可确保它们互斥 在一个问题中。
  • value属性决定了什么 checked绑定将用于其值
  • checked绑定将 使用选项的值
  • 设置option.Value

以下是一个示例:http://jsfiddle.net/rniemeyer/ncERd/