How can I bind the selected text of a Select box to an object's attribute with Knockout JS, or anything else?

StackOverflow https://stackoverflow.com/questions/4785481

문제

I have a select box pull down that I'm populating with a JSON list returned from a stored procedure, but unfortunately when I update the linked object I need to return the selected text of the pulldown, not the selected index like one would think (poor database design, but I'm stuck with it for now and cannot change it).

Does anyone have any ideas what I can do to keep the selected text synced with the appropriate javascript object's attribute?

도움이 되었습니까?

해결책

So yes, you got what I was getting at. Use the text as the value for the select options rather than using an index. The value really should be something useful, I can't think of any case where I've ever used an index. A number sure, but a number that relates to the application's models in some way (like an id from a database), not to the number of items in the select box.

Well done.

다른 팁

You could keep both, the value and the text, if you use subscribers. For instance, if each of your javascript objects look like this:

    var optionObject = {
       text:"text1"
       value: 1
    }

Then your binding would look like:

Where 'OptionsObjects' is a collection of optionObject and selectedOption has two observable properties: text and value. Finally you subscribe to the value property of the selectedOption:

    viewModel.selectedOption.value.subscribe(function(newValue){
        var optionText = viewModel.OptionsObjects[newValue].text;
        viewModel.selectedOption.text(optionText);
    });

Then if you want to see the new selected option text when the value is changed, you could have a binding as follows:

    <span data-bind:"text:selectedOption.text"></span>

In your particular case you would return selectedOption.text().

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top