简体   繁体   English

如何设置动态生成的下拉列表或多项选择的值?

[英]How to set value of drop down list or multiple select that was generated dynamically?

The problem statement over here is that I have a select list which is being populated by handlebar with the help of JSON data from server as shown in data_option variable and then there is other response from server store in data variable which is the actual data to be set for select list. 此处的问题陈述是,我有一个选择列表,该列表由车把在来自服务器的JSON数据的帮助下进行填充,如data_option变量所示,然后服务器存储在data变量中的其他响应是实际的数据为选择列表设置。 As I have already specify the value while compiling data but still it doesn't selects the value and when I use Jquery to retrieve it throws empty. 因为我已经在编译数据时指定了值,但是仍然没有选择该值,并且当我使用Jquery检索它时,它会为空。

<div class="make">
    <script type="text/x-handlears-template" id="make">
        <select class="options" value="{{id}}">
            <option value="">--</option>
        </select>
    </script>
</div>

<script type="text/x-handlears-template" id="options">
    {{#each option}}
        <option value="{{id}}">{{name}}</option>
    {{/each}}
</script>
<script type="text/javascript">
var data = {"id": 3};
var data_options = {
    "option":[
        {
            "id": 1,
            "name": "John Doe"
        },
        {
            "id": 2,
            "name": "James Don"
        },
        {
            "id": 3,
            "name": "John Don"
        },
        {
            "id": 4,
            "name": "James Doe"
        }
    ]
}
var source = $('#make').html();
var template = Handlebars.compile(source);
$('.make').append(template(data));
var source2 = $('#options').html();
var template2 = Handlebars.compile(source2);
$('.options').append(template2(data_options));
</script>

You have to set the selected attribute on the option you wish to select. 您必须在希望选择的选项上设置selected属性

You could for example modify your data to set a flag indicating the selection state: 例如,您可以修改数据以设置一个指示选择状态的标志:

var i, opt;
for (var i=data_options.option.length-1; i>=0; i--) {
    opt = data_options.option[i];
    if (opt.id === data.id) {
        opt.selected = true;
        break;
    }
}

var source2 = $('#options').html();
var template2 = Handlebars.compile(source2);
$('.options').append(template2(data_options));

and use {{#if selected}} ... {{/if}} in your template accordingly 并在模板中相应地使用{{#if selected}} ... {{/if}}

<script type="text/x-handlears-template" id="options">
    {{#each option}}
        {{#if selected}}
            <option value="{{id}}" selected="selected">{{name}}</option>
        {{else}}
            <option value="{{id}}">{{name}}</option>
        {{/if}}
    {{/each}}
</script>

http://jsfiddle.net/nikoshr/p588kp0L/ http://jsfiddle.net/nikoshr/p588kp0L/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM