将元素的可见性绑定到另一个元素

Bind visibility of element to another element?

本文关键字:元素 另一个 绑定 可见性      更新时间:2023-09-26

我希望只有当另一个元素的值不为空时,元素才可见。

现在我正在使用:

function setReceiveSmsNotificationsCheckboxArea() {
  var checkbox = $('#ReceiveSmsNotifications');
  var value = !!$('#Cellphone').val().trim(); //bool depending on txt val
  checkbox.prop('checked', value);
  checkbox.closest('.form-group').toggle(value);
}
$('#Cellphone').change(function () {
  setReceiveSmsNotificationsCheckboxArea();
});
$(document).ready(setReceiveSmsNotificationsCheckboxArea);

有没有办法将后两个函数合并为一个(这样更改甚至在启动时也会运行?)

您可以在页面加载时触发更改事件以触发处理程序

function setReceiveSmsNotificationsCheckboxArea() {
  var checkbox = $('#ReceiveSmsNotifications');
  var value = !!$('#Cellphone').val().trim(); //bool depending on txt val
  checkbox.prop('checked', value);
  checkbox.closest('.form-group').toggle(value);
}
$('#Cellphone').change(setReceiveSmsNotificationsCheckboxArea).change();