0
votes

I am trying to access both the value and the text that is within a select list so that I can store the values to display the users selection in another part of my application.

I have the value binding to an object without any trouble, however I was wondering if it was possible to access the text attribute and bind that also to my object.

I am dynamically building my answers for the dropdown from a json object from the database which renders the questions for the form (which can be 1 or many).

My binding for the questions looks like this:

<div data-bind="text: QuestionText" class="caf-question sub-unit-1-bottom"></div>
                <select class="inline" data-bind="value: SelectedComparisonOperator">
                    <option value="0">Equal to</option>
                    <option value="1">Not equal to</option>
                </select>
                <select data-bind="foreach: Answers, visible: Answers.length > 0, value: SelectedAnswerOption" class="caf-answers">
                    <option class="caf-answer" data-bind="text: AnswerText, value: AnswerId, css: {'caf-header': IsHeader == true}"></option>
                </select>

and when I am pushing those items to the knockout context I am populating the following:

QuestionId: 2
QuestionText: "Site"
SelectedAnswerOption: 23
SelectedAnswerOptionText: null
SelectedComparisonOperator: "0"

the values are pushed into the object using:

var clinicalAnswerItem = {
                        QuestionId: item.QuestionId,
                        QuestionText: item.QuestionText,
                        SelectedAnswerOption: item.SelectedAnswerOption,
                        SelectedAnswerOptionText: "Need to populate this somehow",
                        SelectedComparisonOperator: parseInt(item.SelectedComparisonOperator)
                    }

                    viewModel.clinicalAnswers.push(clinicalAnswerItem);

Ideally, I'd like to just take the text from the select option and push that into the knockout context. Is this possible?

Many thanks

1

1 Answers

0
votes

If you bind your options against an array of objects, then value can be populated with the selected object and you can access the text/value off of it like:

this.myOptions = [
  { value: 0, text: "zero" },
  { value: 1, text: "one" }
];

Then bind like:

<select data-bind="options: myOptions, optionsText: 'text', value: mySelection"></select>

Now, mySelection would be populated with an object that you could access the value and text properties off of.