简体   繁体   中英

Javascript search for dropdown inside knockout data-bind foreach

Using knockout js

I have setup my dropdown inside a table as:

 <tbody data-bind="foreach: items">
<tr>
  <td id="tdName"><select class="form-control" data-bind="options: $parent.ddl, optionsText: 'firstName', value: selectedValue, optionsCaption: '--Select--',  attr: { name: 'Items[' + $index() + '].Name', id: 'Items[' + $index() + '].Name'}"> </select></td>
 </tr>

So it creates multiple rows of dropdowns. The above in html looks as below:

<select class="form-control" data-bind="options: $parent.ddl, optionsText: 'firstName', value: selectedValue, optionsCaption: '--Select--',  attr: { name: 'Items[' + $index() + '].Name', id: 'Items[' + $index() + '].Name'}" name="Items[0].Name" id="Items[0].Name"><option value="">--Select--</option><option value="">Alex</option><option value="">Sam</option> </select>

I have a save button where I want to validate if this dropdown was selected on or not.

So I am trying to use the below code on save button click:

     var selectList = $('#tdName > select');         
        for (var ddl of selectList ) {               
            if (ddl.value == '') {
                ddl.className = "required text-danger form-control ddl-error";                }
        }

In my console when I debug I can see the selectList as: select#Items[0].Name.form-control

So basically what I am trying to do above is loop through all the ddl and if no selection is made add the error class to it so that it is highlighted.

The issue is ddl.value is always '' so the dropdown is always highlighted.

Not sure here if I am looping though correctly here

I have my jsfiddle here as:

https://jsfiddle.net/aman1981/7wqvr854/51/

To see in action click add row, get data to populate the dropdown.

Would appreciate inputs.

You shouldn't access the DOM to check for selected values. You're already binding them to your viewmodel!

The validity check inside the Save method can access items directly:

self.save = function() {
  var rows = self.items();

  if (!rows.length)
    alert("You cannot save an empty table");
  else if (!rows.every(r => r.selectedSeperator()) 
    alert("Some rows do not have a selected seperator");
  // etc.

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM