333Matt
333Matt

Reputation: 1188

Why does an extremely simple knockout binding not work for a select box?

This should be the easiest thing in the world. Here's the line in my viewModel:

self.trueOrFalse = ko.observableArray(['false', 'true']);

And here's the form where I attempt to bind, but end up with an empty dropdown...

                <form data-bind="submit: addItem">

                    <label>Category</label><br/>
                    <div>
                        <select data-bind="options:categories, optionsText: 'Name', value: newItem.Category"></select>
                    </div><br/>


                <div class="form-group" data-bind="with: newItem">
                    <label>Name</label><br/>
                    <div>
                        <input type="text" class="form-control" id="inputName" data-bind="value:Name" />
                    </div>

                    <label>Description</label><br/>
                    <div>
                        <input type="text" rows="3" class="form-control" id="inputDescription" data-bind="value:Description"/>
                    </div>

                    <label>Price</label>
                    <div>
                        <input type="number" step="any" class="form-control" id="inputPrice" data-bind="value:Price" />
                    </div>

                    <label>Vesselizable?</label>
                    <div>                            
                        <select data-bind="options: trueOrFalse"></select>
                    </div>

                </div>
                <button type="submit" class="btn btn-default">Add</button>
            </form>

That first select for Category is pulling data from an API and works just fine. But the simple one at the bottom won't bind to the hardcoded array.

Upvotes: 0

Views: 39

Answers (1)

chris vietor
chris vietor

Reputation: 2060

I can just guess, because you only show one line of your viewmodel, but i think the error might be a context error... is the trueOrFalse observableArray on the newItem observable?

<div class="form-group" data-bind="with: newItem">
  ...

    <label>Vesselizable?</label>
    <div>                            
      <select data-bind="options: trueOrFalse"></select>
    </div>

  ...
</div>

knockout looks for a the trueOrFalse array on the newItem because of your WITH binding, you may wanna change that to

<select data-bind="options: $parent.trueOrFalse"></select>

or even

<select data-bind="options: $root.trueOrFalse"></select>

As Jamiec pointed out in the comments, have a look at the console...

Upvotes: 1

Related Questions