In a form I have a select box with several options, each representing a report with various variables which influence the rest of the form. Some reports require a start date, others an end date, some require both. I have bound the requirements for each of the reports to the option-elements like this:
<select data-bind="value: ReportId">
<option value="ID" data-hasStartDate="BOOL" data-hasEndDate="BOOL">Report name</option>
</select>
<input data-bind="visible: hasStartDate" />
<input data-bind="visible: hasEndDate" />
with ID being the id of the report and BOOL being either true or false. I use knockout to data-bind the value of the select-box to the reportId. But I could not figure out how to bind the hasStartDate and hasEndDate-values to a Knockout observable in order to show the appropriate form elements.
Even with custom bindings, I needed a normal jQuery onChange-event in order to apply the values to the Knockout-values hasStartDate and hasEndDate. Is it possible to do it entirely with Knockout itself?
Have you tried using the options binding for select boxes?
You also can't bind knockout using data-whatever="some value". You always use data-bind, like so: data-bind="bindingtype: value".
Edit:
That being said... If you want to get the data from a selected option in a <select> element, I would use the following jQuery:
$("select").on('change', function() {
var selectedData = $(this).find(":selected").data("stuff");
});
You can then use selectedData and apply this to a knockout view model.
Working example in a fiddle: http://jsfiddle.net/RZq6Q/4/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With