【问题标题】:Jquery Chosen get the Id of un-selected value in dropdownJquery选择在下拉列表中获取未选择值的ID
【发布时间】:2016-04-19 09:07:54
【问题描述】:

我已经设法获得Chosen plugin 的选定选项的ID。这是jsfiddle Demo

现在我不确定如何获取未选择选项的 ID。我正在使用此代码来获取所选选项的 id。

 var SelectedIds = $(this).find('option:selected').map(function() {
      if ($(this).attr('value') == params.selected)
        return $(this).prop('id')

    }).get();
    alert(SelectedIds);

【问题讨论】:

  • 您想在选择任意数量的选项后获取所有未选择选项的 id 吗?
  • @itzmukeshy7 。基本上我只想要当前未选择的选项的 ID。例如,如果在下拉列表中选择了国家美国。当用户取消选择美国时。我想得到它的ID。其他国家也一样。
  • 当用户取消选择任何选定的选项时,您想在此处执行某些功能对吗?
  • @itzmukeshy7 是的! :)

标签: javascript jquery jquery-chosen


【解决方案1】:

当取消选择某个选项时,您会收到更改事件,但 params 对象有一个 deselected 属性,您可以像使用 selected 一样使用它。

我做了一个jsfiddle给你演示:http://jsfiddle.net/1eut1c3d/

$("#chosen").chosen().on('change', function(evt, params) {

  if (params.selected !== undefined) {
     var selectedID = $(this).find('option:selected').map(function() {
        if ($(this).attr('value') == params.selected)
        return $(this).prop('id')
   }).get();
   alert("Selected: " + selectedID);
}
if (params.deselected !== undefined) {
    var deselectedID =   $(this).find('option').not(':selected').map(function() {
      if ($(this).attr('value') == params.deselected)
        return $(this).prop('id')  
       }).get();
       alert("Deselected: " + deselectedID);
    }
});

【讨论】:

  • 所以.not(':selected') 是我缺少的关键元素..谢谢
  • 不客气。您实际上并不需要该部分,因为您只需执行 $(this).find('option').map(...) 即可找到所有选项,但添加 .not(':selected') 会对其进行过滤并使其更快找到,我认为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
  • 2013-10-06
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多