如果选择1st或2nr,则禁用第3个,第4个下拉列表

时间:2016-09-26 18:23:34

标签: javascript jquery

我有这个问题:在我的表单中有4个下拉列表,当选择第1个(category1)或第2个(software1)下拉列表时,必须禁用第3个(category2)和第4个(software2)。

对于这个问题,我在disable-second-dropdown-if-the-first-is-not-selected找到了这个脚本,但我不相信要修改它:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
category1
<select name='cat1'>
  <option value='0'>Select one</option>
  <option value='1'>little</option>
  <option value='2'>good</option>
</select>

software1
<select name='soft1'>
  <option value=''>Select one</option>
  <option value='W'>Word</option>
  <option value='E'>Excel</option>
  <option value='PP'>Power Point</option>
</select>

<br />
category2
<select name='cat2'>
  <option value='0'>Select one</option>
  <option value='1'>little</option>
  <option value='2'>good</option>
</select>

software2
<select name='soft2'>
  <option value=''>Select one</option>
  <option value='W'>Word</option>
  <option value='E'>Excel</option>
  <option value='PP'>Power Point</option>
</select>

<script type="text/javascript">
var setEnabled = function(e) {
  var name = this.name.replace(/1/, '2'); //get name for second drop down
  $('select[name=' + name + ']')
      .prop('disabled', 0 === this.selectedIndex) // disable if selected option is first one
};

$(function() {
  $('select[name=cat1], select[name=soft1]')
      .on('change', setEnabled)
      .trigger('change'); // trigger on page load
});
</script>

如何修改?

由于

1 个答案:

答案 0 :(得分:2)

我认为你想要的主要是为===

翻转!==

然而,为了使这个工作在矩阵上,其中两个顶部输入触发两个底部输入的启用/禁用,您将需要在两者的更改时测试两者。

var setEnabled = function(e) {
  var selected = $('select[name=cat1]').prop('selectedIndex') > 0 || $('select[name=soft1]').prop('selectedIndex') > 0;
  $('select[name=cat2], select[name=soft2]').prop('disabled', selected); // disable if selected option is first one
  if (selected) {
    $('select[name=cat2], select[name=soft2]').prop('selectedIndex', 0)
  }
};

$(function() {
  $('select[name=cat1], select[name=soft1]')
      .on('change', setEnabled)
      .trigger('change'); // trigger on page load
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</script>
category1
<select name='cat1'>
  <option value='0'>Select one</option>
  <option value='1'>little</option>
  <option value='2'>good</option>
</select>

software1
<select name='soft1'>
  <option value=''>Select one</option>
  <option value='W'>Word</option>
  <option value='E'>Excel</option>
  <option value='PP'>Power Point</option>
</select>

<br />
category2
<select name='cat2'>
  <option value='0'>Select one</option>
  <option value='1'>little</option>
  <option value='2'>good</option>
</select>

software2
<select name='soft2'>
  <option value=''>Select one</option>
  <option value='W'>Word</option>
  <option value='E'>Excel</option>
  <option value='PP'>Power Point</option>
</select>