无法遍历选择列表中的选项

时间:2020-01-22 14:27:08

标签: javascript jquery

我有这个选择列表,如下:-

enter image description here

<input type="text" value="Departmental Folder Structure Clean up" maxlength="255" id="Title_fa564e0f-0c70-4ab9-b863-0177e6ddd247_$TextField" title="Title Required Field" style="ime-mode : " class="ms-long ms-spellcheck-true" disabled="disabled">
<select id="ProjectDependantProjectsLookup_b60c7117-fab9-43ec-8c10-4e714969dd20_SelectCandidate" multiple="multiple" title="Active Dependant Projects possible values" style="width: 300px; height: 125px; overflow: scroll;">
<option value="68" title=" .......Laptop/PC replacement Project"> ... Laptop/PC replacement Project</option>
<option value="83" title="3.....Deployment ">... Deployment </option>
<option value="108" title=".....sion">...g Session</option></select>

现在我要删除平铺字段具有标题=的选项,因此我尝试了此操作:-

var titlevalue = $('input[id^="Title_"]').val();
var currentprojecttitle = $($("[id^=ProjectDependantProjectsLookup_][id$=_SelectCandidate]")[0]);
for (var i=0; i<currentprojecttitle.length; i++) {
   if (currentprojecttitle.options[i].value == titlevalue)
      currentprojecttitle.remove(i);
}

但我收到此错误:-

未捕获的类型错误:无法读取未定义的'0'属性

尽管在我的情况下,$($("[id^=ProjectDependantProjectsLookup_][id$=_SelectCandidate]")[0])正确地引用了选择列表,因为当我运行此$($("[id^=ProjectDependantProjectsLookup_][id$=_SelectCandidate]")[0]).css('width','300px');时,它会增加宽度。

2 个答案:

答案 0 :(得分:1)

我认为设置var currentprojecttitle = $("[id^=ProjectDependantProjectsLookup_][id$=_SelectCandidate]")[0];更简单。在代码中,将其包装到jquery变量中,然后将其用作javascript变量。您可以看到一个演示here。我在Deployment选项中添加了相应的类,然后将其删除。

答案 1 :(得分:0)

问题是您正在处理select的jQuery元素。您必须这样做:

var titlevalue = $('input[id^="Title_"]').val();
var currentprojecttitle = $($("[id^=ProjectDependantProjectsLookup_][id$=_SelectCandidate]")[0]);
for (var i=0; i<currentprojecttitle.length; i++) {
   if (currentprojecttitle[0].options[i].value == titlevalue)//Selecting the first element of the jQuery collection
      currentprojecttitle[0].remove(i);
}
相关问题