简体   繁体   English

Javascript搜索击倒数据绑定foreach中的下拉列表

[英]Javascript search for dropdown inside knockout data-bind foreach

Using knockout js 使用淘汰赛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: 上面的html如下所示:

<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 在控制台中,当我调试时,可以看到selectList为: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. 因此,基本上我想在上面执行的操作是遍历所有ddl,如果未进行选择,则将错误类添加到其中,以便突出显示它。

The issue is ddl.value is always '' so the dropdown is always highlighted. 问题是ddl.value始终为'',因此下拉菜单始终突出显示。

Not sure here if I am looping though correctly here 不确定这里是否正确循环

I have my jsfiddle here as: 我在这里有我的jsfiddle:

https://jsfiddle.net/aman1981/7wqvr854/51/ 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. 您不应该访问DOM来检查选定的值。 You're already binding them to your viewmodel! 您已经将它们绑定到您的视图模型!

The validity check inside the Save method can access items directly: Save方法中的有效性检查可以直接访问以下items

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.

};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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