jsViews - how do I set selected option from data

2019-06-05 21:44发布

问题:

I have a select which is bound to some values from the server using jsViews. I have successfully managed to show the options but I want be able to track and set the select option to the value from my JavaScript object. This is my code:

<select id="albumChoice" data-link="selectedAlbum">
    <option value="-">Please select</option>
    {^{for albums}}
    <option data-link="{value{:id} text{:name}} selected{:selectedAlbum}}"></option>
    {{/for}}
</select>

The complete example code is in this fiddle: http://jsfiddle.net/4ZevT/

As you can see I have tried to use selected{:selectedAlbum} but that doesn't do anything. What must I do so that the option is automatically set when the page loads to the value from the server.

回答1:

There is an example here:

http://www.jsviews.com/#jsvplaying. (See at the end of the section: Sample: data-linking to <select>... and much more...)

I have updated your fiddle here: http://jsfiddle.net/4ZevT/2/

You syntax for data-link on the <option... has some errors. I updated it to:

<option data-link="value{:id} {:name} selected{:id == ~root.selectedAlbum}"></option>

The selected binding expects a Boolean, not a number...

I had to set selected{:id == ~root.selectedAlbum} rather than selected{:id === ~root.selectedAlbum} because you are using number values for you ids. If you change them to strings, you can switch to ===.