Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout javascript data-bind dropdown list

for a few days I've started working with knockout javascript and bootsrap. I want to add some elements into a dropdown list, elements from database and to get the id (database) for the clicked to search other data. I add the data from the controller:

success: function (data) {
            if (data != null) {
                $.each(data, function (index, element) {
                    document.pvm.CartLst.push({ Id: element.ID, Name: element.ShortName });
                });
            }
        }

And I add that data into the dropdown list:

_mVM.Averagepace = function (item, event) {
        var element = {cartlist: document.pvm.CartLst()}; 
        var rvm = new panelViewModel(element);
        _mVM.rapArray.push(rvm);
    }

In .cshtml I have this:

<ul class="dropdown-menu scrollable-menu" aria-labelledby="dropdownMenu6" data-bind="foreach: cartlist">
<li data-bind="click: document.pvm.changeSelC"><a href="#"><b data-bind="text: $data"></b></a></li></ul>

When the selection changes it calls this:

_mVM.changeSelC = function (item, event) {

            //get the id of the selected cart from the dropdownlist

            }

The problem is that in my dropdown appears a list of "[object Object]" but it must display only the Names from CartLst. And when the selection changes to get the id behind that name inside _mVM.ChangeSelC. I've searched for different solution but nothing to work for me. If you can help me with it I'll appreciate.

like image 356
Alex Mihai Avatar asked Jul 11 '26 15:07

Alex Mihai


1 Answers

This is how you typically get "[object Object]" in a dropdown with KnockoutJS:

ko.applyBindings({ availableItems: [{Id: 1, Name: 'some item'}] });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="options: availableItems"></select>

This is in fact logical if you think about it: the options are bound to the objects in the array. You already allude to it: you need to tell Knockout to use the name property of items for displaying an option. This is documented in the options binding, and uses the optionsText binding, like so:

ko.applyBindings({ availableItems: [{Id: 1, Name: 'some item'}] });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="options: availableItems, optionsText: 'Name'"></select>
like image 194
Jeroen Avatar answered Jul 14 '26 04:07

Jeroen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!