如何将jquery中的forEach值与选定的下拉值进行比较

时间:2019-01-30 08:51:42

标签: javascript jquery html

var externalData = [{ "sedesc": "TAX 1040-2000" },
                    { "sedesc": "TAX 1040-2005" }
                   ];
      var extData;      
   externalData.forEach(function (data) {
      console.log(data.sedesc)
      extData = data.sedesc
   })
onApprove: function(){
if ($('#extservicecode option:selected').text() === extData ) {
       alertify.error("Duplicates are not allowed");                              
   }
}}

这是我的jquery代码。我有一个下拉列表($('#extservicecode option:selected').text()),如果我选择以上任何一个值"data.sedesc",它都会显示一条错误消息。我需要将所选值与已经存在的值进行比较。

更新

externalData.forEach(function (data) {
                console.log(data.Scdesc)
                duplicatedData = data.Scdesc
            })
if ($('#extservicecode option:selected').text() === duplicatedData) {
        alertify.error("Duplicates are not allowed");                              
    } 

2 个答案:

答案 0 :(得分:1)

获取更改后的值,然后将所选值与数组中的值进行比较。

$('button').on('click', function() {
  const value = $('#extservicecode option:selected').text();

  externalData.forEach(function (data) {
      if (value === data) {
        // duplicate value found
      }
  });
});

根据您的onApprove方法

onApprove: function(){
  // Get the dropdown value
  const duplicateData = null;
  const value = $('#extservicecode option:selected').text();

  // iterate over external data
  externalData.forEach(function (data) {
    // check if dropdown value has one of the duplicate value
    if (value === data) {
      duplicateData = data;
      // duplicate value found
     }
  });

  // duplicateData can be used here
  // dropdown value is valid
}

答案 1 :(得分:1)

您需要侦听下拉列表的SELECT bhk.u_manager, leaderboard.total_pts from bhk LEFT JOIN leaderboard on bhk.u_id=leaderboard.u_id and league_members.l_id=1; 事件,并将该if语句放入事件处理程序中。

change