Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected values from dynamically created dropdowns

I'm using KnockoutJS and durandalJS 2.0. I'm dynamically adding two drop-downs based on the database table entries and populating them with data form another table. Each drop-down also has a check-box. How do I get the selected drop-down values?

enter image description here

models

var dataToAdd = {
    mydata_Id: ko.observable(),
    mydata_Name: ko.observable(),
    mydata_data: ko.observableArray([dataTask])
};

var dataTask = {
    taskId: ko.observable(),
    dropdownId: ko.observable()
};

var taskList=ko.observableArray([]);//get data from database table. Consider there are two entries.
var dropdownData=ko.observableArray([]); //get the dropdown data

View

//Since *taskList* has two entries, two dropdowns with their respective checkbox will get generated.
<div data-bind="foreach:taskList">
    <label><input type="checkbox" data-bind="checked: true" />
    <span data-bind="text:Name"></span></label>    

    <select data-bind="options: $root.DropdownData, optionsValue: 'Id', optionsText: 'Name', optionsCaption: 'Select...', value: $root.dataTask.dropdownId</select>
</div>

First: How do I get the selected value for each drop-down when I hit the ADD button? When I use the value: $root.dataTask.dropdownId, both of the drop-downs get changed to the same selected value. When I check the checkbox, dropdown should be enabled and after selecting, I should be able to update a observable Array like below:

{taskId:44,dropdownId:10},{taskId:55,dropdownId:11}

Second: Also, when I uncheck the check-box, the respective drop-down should get disabled and the entry should be reomoved from the observable Array.

like image 595
IRONMAN Avatar asked Dec 03 '13 06:12

IRONMAN


1 Answers

Your question has a lot of uncertainty to it, nevertheless I have included a working fiddle demonstrating what you are looking for -

http://jsfiddle.net/Lxt7E/1/

<div data-bind="foreach: Dropdowns">
    <label><input type="checkbox" data-bind="checked: checkedObs" />
    <span data-bind="text: label"></span></label>    

    <select data-bind="disable: checkedObs, options: theseOptions, optionsText: 'Name', optionsCaption: 'Select...', value: selectedOption"></select>
</div>

<button data-bind="click: addButton">Add</button>

In a nutshell, what you can do is create instances of a model such as 'dropdown' in this case and use Knockout's foreach binding to render n number of them. The instance of a dropdown contains the observables that do what you are looking for and could be used in the add function to decide whether to write the values or w/e

like image 127
PW Kad Avatar answered Oct 04 '22 12:10

PW Kad