jQuery templates and selects… “tag” way of producing a select pulldown with an option selected?

StackOverflow https://stackoverflow.com/questions/4737503

  •  12-10-2019
  •  | 
  •  

سؤال

I was wondering if anyone knew of a way I could write a jQuery template (using template tags only) to create a select pull down with an option selected. I already have an object with two parameters: the key/value list of options and the selected option. To make matters worse: I don't have the index of the selection, I only have the option string.

var optionObj = { optionsList: jsonlist, selectedOption: selectedOptionText };

I have been using KnockoutJS and it works great, but (as far as I can see) it doesn't suport option selection based upon the option text value.

Any ideas?

I just came up with this, but maybe there's a better way?

<script id="tmplTextOptions" type="text/x-jquery-tmpl">
    {{each optionsList}}
        <option value="${Key}"
        {{if Value==selected}} selected="selected" {{/if}}
        >${Value}</option>
    {{/each}}
</script>
هل كانت مفيدة؟

المحلول

You could add a selected property to each option in your optionsList and store 'selected="selected"' for the selected one. Then in each option you can output something like this:

<option value="${Key}" ${Selected}>${Value}</option>

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top