避免重复的javascript

时间:2017-04-01 12:44:56

标签: javascript checkbox textbox

我有一个HTML表单,其中包含大约30条相似的行。每一行都是这样的:

<tr>
  <td>Car Park</td>
  <td><input type="checkbox" id="local_parking" name="amenity[]" value="local_parking"></td>
  <td><input type="text" id="local_parking_t" name="amenity_text[]" value="Car park"></td>
</tr>

如果未选中该复选框,则需要禁用该文本框以避免将其值传递给后面的mySQL查询。我可以用这个javascript一行做到这一点:

document.getElementById('local_parking').onchange = function() {
  document.getElementById('local_parking_t').disabled = !this.checked;
};

然而,用不同的ID重复javascript 30次似乎是不合理的混乱。还有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

捕获每个checkbox并绑定change事件侦听器。如果用户检查指定checkbox - 启用相应的text输入。

var checkboxes = document.querySelectorAll('input[type=checkbox]'),
    inputs = document.querySelectorAll('input[type=text]');
    
    [...checkboxes].forEach((v,i) => v.addEventListener('change', function(){
      inputs[i].disabled = !this.checked;
    }));
<tr>
  <td>Car Park</td>
  <td><input type="checkbox" id="local_parking" name="amenity[]" value="local_parking"></td>
  <td><input type="text" id="local_parking_t" disabled name="amenity_text[]" value="Car park"></td>
</tr>
<br>
<tr>
  <td>Some txt</td>
  <td><input type="checkbox" id="local_parking" name="amenity[]" value="local_parking"></td>
  <td><input type="text" id="local_parking_t" disabled name="amenity_text[]" value="Car "></td>
</tr>

答案 1 :(得分:0)

您可以使用公共类来定位CHECKBOX元素,然后使用DOM遍历方法来定位INPUT元素。

&#13;
&#13;
var elements = document.querySelectorAll('.local_parking');
elements.forEach(function(element) {
  element.addEventListener('change', function() {
    this.parentNode.nextElementSibling.childNodes[0].disabled = !this.checked;
  });
});
&#13;
<table>
  <tr>
    <td>Car Park</td>
    <td><input type="checkbox" class="local_parking" name="amenity[]" value="local_parking"></td>
    <td><input type="text" class="local_parking_t" name="amenity_text[]" value="Car park" disabled></td>
  </tr>
  <tr>
    <td>Car Park</td>
    <td><input type="checkbox" class="local_parking" name="amenity[]" value="local_parking"></td>
    <td><input type="text" class="local_parking_t" name="amenity_text[]" value="Car park" disabled></td>
  </tr>
</table>
&#13;
&#13;
&#13;