javascript – 由于隐藏的选择元素,按钮被禁用

我有一个包含三个选项的表单:

>适合
>颜色
>尺寸

默认情况下,“适合”下拉菜单和“颜色”下拉列表处于活动状态且已选择默认值(例如常规适合和蓝色).

有三种不同的“尺寸”下拉菜单,但根据从“适合”下拉列表中选择的内容,任何时候只能看到一个.

如果选项值=“无”,则禁用按钮.

问题

只有当所有三个“大小”下拉列表都被更改以使其值不是“无”时,Button才会变为活动状态(这可以通过选择Regular的初始大小,然后从’Fit’下拉列表中选择Petite和Long来完成).理想情况下,我只希望按钮考虑活动的“大小”下拉列表.

更新

下面是@nagappan提供的jsFiddle解决方案,非常感谢.

https://jsfiddle.net/dodgers76/c0dvdwbz/

var currentSelectedVals = {'selector-fit':'','selector-color':'','selector-sizes':''};
var disableComboVals = [
{'selector-fit':'','selector-color':'','selector-sizes':'none'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'10'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'20'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'22'},
{'selector-fit':'petite','selector-color':'','selector-sizes':'24'},
{'selector-fit':'long','selector-color':'','selector-sizes':'22'},
{'selector-fit':'long','selector-color':'','selector-sizes':'24'}
];
function checkDisableCombo() {
return $.grep(disableComboVals, function(vals){
  cnt = 0;
  $.each(vals, function(key,val) {
     console.log('comparing key val '+key+val);
     if (val === '' || val === currentSelectedVals[key]) {
         console.log('>>matched values');
         cnt = cnt + 1;
     }
  });
  if (cnt===3) {
     return true;
  }
  return false;
});
};
$(function(){
var sizeVal = 'none';


  $("select.selector-fit").on("change", function(){
    //remove active
    $("select.selector-sizes.active").removeClass("active");
    //check if select class exists. If it does then show it
    var subList = $("select.selector-sizes."+$(this).val());
    if (subList.length){
      //class exists. Show it by adding active class to it
      subList.addClass("active");
      subList.val(sizeVal);
    }
  });

  $('.selector-sizes').on('change', function() {
    sizeVal = $(this).val();
  });
});

$(function() {
  $('.selector').on('change', function() {
    var $sels = $('option.selector-sizes:selected[value="none"]');
    var isSizeSelector = jQuery.inArray( "selector-sizes",this.classList);
    currentSelectedVals[this.classList[1]] = this.value;
    console.log(currentSelectedVals);
    var result = checkDisableCombo();
    console.log(result);
    if ( result.length > 0) {
        console.log('disabled false');
        $("#Testing").attr("disabled", true);
    } else {
        $("#Testing").attr("disabled", false);
    }
  }).change();
});

最佳答案 如果我们想要通过组合下拉选择的值来禁用按钮.我们可以有一个全局变量来跟踪三个下拉列表中当前选定的值.只有我们可以拥有一系列的分配组合.因此,无论何时用户选择一个值,我们都会与禁用组合交叉检查,如果匹配,我们可以禁用该按钮.验证组合可以如下完成.更新了jsfiddle链接.
JS FIDDLE UPDATED

function checkDisableCombo() {
return $.grep(disableComboVals, function(vals){
  cnt = 0;
  $.each(vals, function(key,val) {
     console.log('comparing key val '+key+val);
     if (val === '' || val === currentSelectedVals[key]) {
         console.log('>>matched values');
         cnt = cnt + 1;
     }
  });
  if (cnt===3) {
     return true;
  }
  return false;
});
点赞