根据递增的选择ID隐藏和显示div

问题描述 投票:0回答:1

我试图隐藏和显示包含在 js/html 动态表中的输入。仅当选择选项时才会显示输入。我试图保留一系列其他选项,以防客户从不同的动态表行中选择其他。 我面临的问题是,它只能在动态添加另一个表行之前起作用 下面是我的html代码

  <table class="table table-bordered table-striped table-hover" id="myTable">
    <tr>
      <td>
       <select class="form-control select2" id="selectId_1" name="myvalue[]" required>
        <option value="val 1">.......</option>
        <option value="Other">Other</option>
     </select>
     <input type="text" class="form-control other" id="other_1" name="other[]" class="form-control " placeholder="other category" ></td>
     <td><input autocomplete="off" class="form-control quantity" id="quantity_1" name="quantity[]" type="number"></td>
     <td>...</td>
   </tr>
 </table>

这是js代码,似乎只适用于第一行

     $('[id^=selectId_]').each(function (i) {
    i++;
    $(this).change(function () {
      if( $(this).val()==="Other"){
        $('#other_'+i).show();
        }
      else{
        $('#other_'+i).hide()
      }
    });
});
javascript html jquery
1个回答
0
投票

如果事件侦听器位于父元素(例如表格)上,则添加新行不是问题。唯一的事情是你需要测试更改事件的目标。

如果您在“其他”输入上使用禁用属性,则该输入不会包含在提交请求中。同时该属性可用于隐藏输入。

$('#myTable').change(function(event) {
  let form = event.target.form;
  if (event.target.type == 'select-one') {
    if (event.target.value == 'Other') {
      form[`other_${event.target.dataset.id}`].disabled = false;
    }
  }
});
input:disabled {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<form name="form01">
  <table class="table table-bordered table-striped table-hover" id="myTable">
    <tr>
      <td>
        <select class="form-control select2" id="selectId_1" data-id="1" name="myvalue[]" required>
          <option value="val 1">.......</option>
          <option value="Other">Other</option>
        </select>
        <input type="text" class="form-control other" id="other_1" name="other[]" class="form-control " placeholder="other category" disabled></td>
      <td><input autocomplete="off" class="form-control quantity" id="quantity_1" name="quantity[]" type="number"></td>
      <td>...</td>
    </tr>
    <tr>
      <td>
        <select class="form-control select2" id="selectId_2" data-id="2" name="myvalue[]" required>
          <option value="val 1">.......</option>
          <option value="Other">Other</option>
        </select>
        <input type="text" class="form-control other" id="other_2" name="other[]" class="form-control " placeholder="other category" disabled></td>
      <td><input autocomplete="off" class="form-control quantity" id="quantity_2" name="quantity[]" type="number"></td>
      <td>...</td>
    </tr>
  </table>
</form>

© www.soinside.com 2019 - 2024. All rights reserved.