简体   繁体   中英

jsrender populate selectbox multiple with already selected options

I want to populate select box through Jsrender.

The code populate the select box correctly, But i am not able to select few value by default. I created a Jsrender helper function for this, but i think the other values are not accessible inside the loop, so that's why the function is not working.

Here is the link to jsfiddle

My html is

<div class="select_placeholder"></div>
<script id="selectbox" type="text/x-jsrender">
<select multiple="multiple" name="">
{{for cats }}
{{include tmpl="#selectbox_options"/}}
{{/for}}
</select>
</script>
<script id="selectbox_options" type="text/x-jsrender" >
    <option value="{{:term_id}}" {{>~selected(term_id, selected)}} >{{:name}}</option>
</script>

and my javascript is

$.views.helpers({

        selected: function(needle,haystack) {
            console.log(haystack);
            if(typeof haystack === "undefined" || haystack === null) { 
                return;
            }
            var count=haystack.length;
            for(var i=0;i<count;i++){
                if(haystack[i]===needle){return 'selected="selected"'; }
            }
            return;
        }
    });
var cates = [
        {'term_id' : 1, 'name' : 'category 1'},
        {'term_id' : 2, 'name' : 'category 2'},
        {'term_id' : 3, 'name' : 'category 3'},
        {'term_id' : 4, 'name' : 'category 4'},
        {'term_id' : 5, 'name' : 'category 5'},

    ];
    var selected = [{'term_id' : 3}, {'term_id' : 4}];
    $( ".select_placeholder" ).html(
        $( "#selectbox" ).render({cats : cates,selected:selected})
   );

Try to combine data for view https://jsfiddle.net/fksj52c6/5/

var cates = [
        {'term_id' : 1, 'name' : 'category 1'},
        {'term_id' : 2, 'name' : 'category 2'},
        {'term_id' : 3, 'name' : 'category 3'},
        {'term_id' : 4, 'name' : 'category 4'},
        {'term_id' : 5, 'name' : 'category 5'},

    ];
    var selected = [{'term_id' : 3}, {'term_id' : 4}];

  for(var i = 0; i< selected.length; i++) {
        for(var j = 0; j < cates.length; j++)
                if(selected[i].term_id === cats[j].term_id) {
            cats[j].selected = true;
        }
    }
$( ".select_placeholder" ).html(
               $( "#selectbox" ).render({cats : cates})
             );

html

<div class="select_placeholder"></div>
<script id="selectbox" type="text/x-jsrender">
<select multiple="multiple" name="">
{{for cats }}
<option value="{{:term_id}}" {{if selected}}selected="selected"{{/if}} >{{:name}}</option>
{{/for}}
</select>
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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