两个选择选项-不需要验证和隐藏选项

时间:2019-07-15 17:14:52

标签: javascript jquery html

我试图根据另一个选择选项上显示的内容显示一组选择选项。我在理解js脚本的逻辑时遇到了一些问题。

示例: 任何有关如何隐藏其他未使用选项的建议

如果电视仅显示值devicetsignalblackscreenother

如果Radio仅显示以下值:devicersignalother

$('#new').find('option').not('[value="device"]').remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>

<form>
  <table>
    <tbody>
      <tr>
        <td>Issue:</td>
        <td>
          <select required id="test" name="test">
            <option value="" disabled selected>Choose an option</option>
            <option value="tv">tv</option>
            <option value="radio">radio</option>
          </select>
        </td>
      </tr>
      <tr>
        <td height="50px" colspan="3"></td>
      </tr>
      <tr>
        <td>What is the problem?</td>
        <td>
          <select id="new" name="new">
            <option value="" disabled selected>Select an option</option>
            <option value="device">device is defect</option>
            <option value="rsignal">radio has no signal</option>
            <option value="tsignal">radio has no signal</option>
            <option value="blackscreen">tv blackscreen</option>
            <option value="other">Other</option>
          </select>
        </td>
      </tr>
      <tr>
        <td><input type="submit" class="submit" value="submit"></td>
      </tr>
    </tbody>
  </table>
</form>

1 个答案:

答案 0 :(得分:1)

我想您打算使用.change,所以当#test下拉菜单更改时,您需要检查其值,然后根据显示/隐藏option进行选择,对吗?

$('#test').change(function() {
  const options = $('#new').find('option').show();
  if ($(this).val() === 'tv') {
    options.not('[value="device"]').hide();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>

<form>
  <table>
    <tbody>
      <tr>
        <td>Issue:</td>
        <td>
          <select required id="test" name="test">
            <option value="" disabled selected>Choose an option</option>
            <option value="tv">tv</option>
            <option value="radio">radio</option>
          </select>
        </td>
      </tr>
      <tr>
        <td height="50px" colspan="3"></td>
      </tr>
      <tr>
        <td>What is the problem?</td>
        <td>
          <select id="new" name="new">
            <option value="" disabled selected>Select an option</option>
            <option value="device">device is defect</option>
            <option value="rsignal">radio has no signal</option>
            <option value="tsignal">radio has no signal</option>
            <option value="blackscreen">tv blackscreen</option>
            <option value="other">Other</option>
          </select>
        </td>
      </tr>
      <tr>
        <td><input type="submit" class="submit" value="submit"></td>
      </tr>
    </tbody>
  </table>
</form>

通知隐藏option不是cross browser