sam
sam

Reputation: 427

Get value from select in knockout

I have a select element bound using ko and it's displaying data perfectly.

<select name="assetTypeID" 
        class="form-control" 
        id="assetTypeID" 
        data-bind="options: $root.personalassettype_dd, 
                   optionsValue: 'id', 
                   optionsText: 'text', 
                   optionsIncludeDestroyed: true,
                   value:typeid">
</select>

I want to show the selected value of this dropdown in a span. What I am trying is:

<span id="spnassetTypeID" data-bind="text: $root.personalassettype_dd.text"></span>

Have gone through this Stack Overflow question but that didn't work, any ideas?

I'm very close to the answer now. If I write:

<span id="spnassetTypeID" data-bind="text: $root.personalassettype_dd()[0].text"></span>

it works for me at displays the value of the item at 0th index as it is harcoded.

But when I try writing this:

<span id="spnassetTypeID" data-bind="text: $root.personalassettype_dd()[typeid].text"></span>

It gives me this error:

Unable to parse bindings.
Message: TypeError: Unable to get property 'text' of undefined or null reference;
Bindings value: text: $root.personalassettype_dd()[typeid].....

So it means that somehow it's not getting 'typeid' when I was it in place of array index.

Note: I also tried passing typeid in quotes, but that didn't work.

Upvotes: 0

Views: 1394

Answers (1)

Adrian
Adrian

Reputation: 1587

The link of the post you gave has a correct answer.

Your text binding in spnassetTypeID should have the value of the value in your select element. And also, remove your optionsValue binding.

The use of optionsValue is for knockout to determine which property of the object (item from your personalassettype_dd) will be used. For example, if I changed the optionsValue to text then the value of typeId will be the text of the selected object. If I removed the optionsValue then the whole selected object will be the value of typeId.

See this fiddle for a minimal example using your markup.

<select name="assetTypeID" class="form-control" id="assetTypeID" data-bind="options: $root.personalassettype_dd, optionsText: 'text', optionsIncludeDestroyed: true,value:typeid"></select>
<span id="spnassetTypeID" data-bind="text: $root.typeid().text"></span>

Upvotes: 2

Related Questions