如何验证select2是否存在错误-无法读取未定义的属性'length'

时间:2020-03-05 11:36:18

标签: jquery jquery-select2

我正在使用的表单有一个select2下拉列表,其填充像

 $('.DropdownPINOption').select2({
     placeholder: '-- Select your PIN --',
     allowClear: true,
     tags: true,
     data: data.data.Table
 });

,当我从另一个数据库迁移数据时出现了问题。因为我要在此下拉列表中填充的值要么为null,要么不是下拉列表中字段的值。

这是我的代码

 if (data.data.Table[0].Current_Permanent_Overseas_Address_PIN_Code != null)
    $("#4txtPin").val(data.data.Table[0].Current_Permanent_Overseas_Address_PIN_Code).change();

这将引发错误:无法读取null的属性“ length”

所以我做到了:

$('#4txtPin option').each(function () {
   if (this.value == data.data.Table[0].Current_Permanent_Overseas_Address_PIN_Code) {
       $("#4txtPin").val(data.data.Table[0].Current_Permanent_Overseas_Address_PIN_Code).change();
   }
});

它没有显示任何错误,并且按预期方式工作。但这感觉不对。 select2有更好的解决方案吗?无效值到来时如何显示占位符?

0 个答案:

没有答案