繁体   English   中英

使用jQuery和两个selects,select2显示的禁用选项的值比select1低?

[英]Using jQuery and two selects, select2 shows disabled options with a lower value than select1?

我一直在使用jQuery和两个选择框,我想根据第一个框中选择的选项更改第二个框中可用的选项,第二个框中可用的选项的值应小于在第一个框中被选中。

这是HTML:

<select class="select1">
  <option value="100">100</option>
  <option value="200">200</option>
</select>

<select class="select2">
  <option value="0">0</option>
  <option value="100">100</option>
  <option value="200">200</option>
  <option value="300">300</option>
</select>

这是jQuery:

var select1 = $(".select1");
var select2 = $(".select2");

select1
.change(function () {

  var select1Value = parseInt($(this).val(),10);

  select2.children().filter(function () {
    return $(this).attr("value") > select1Value;
  }).each(function () {
    $(this).attr('disabled', 'disabled')
  });

})
.change();

这是一个小提琴。

此处发生的是在初始化时.select2中值为200和300的选项被禁用。 当我将select1更改为200时,我希望发生的事情是select2中的值为300的选项被禁用,但是应该禁用以前被禁用的,现在有效的选项,但事实并非如此,因为初始化时会发生什么。

如果有人能指出我在使用此逻辑的地方出了问题,那将不胜感激,在此先感谢您!

在select1中每次更改值时,已禁用的值都必须删除“ disabled”属性。 因此,首先更改select1的值,然后删除select2中所有选项的禁用状态,然后检查value是大于还是小于。

代码如下:

var select1 = $(".select1");
var select2 = $(".select2");

select1
.change(function () {

  var select1Value = parseInt($(this).val(),10);

  select2.children().each(function () {
    $(this).prop('disabled', false);
  });

  select2.children().filter(function () {
    return $(this).attr("value") > select1Value;
  }).each(function () {
    $(this).prop('disabled', true);
  });

}).change();
var select1 = $(".select1");
var select2 = $(".select2");

select1
.change(function () {
  select2.children().each(function () {
    $(this).removeAttr('disabled')
  });
  var select1Value = parseInt($(this).val(),10);
  select2.children().filter(function () {
    return $(this).attr("value") > select1Value;
  }).each(function () {
    $(this).attr('disabled', 'disabled')
  });

  })
.change();

暂无
暂无

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

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