如何将JavaScript恢复为原始状态

时间:2019-05-05 16:39:24

标签: javascript jquery

不确定标题是否足够清晰,但是我有两种形式,一种形式为uk_inputs,另一种形式为international_inputs。当uk_input中有一个值时,我想禁用所有国际输入。这目前有效(仅使用第一个uk_input尚不确定如何对它们全部进行for_each),但是当uk_input的值返回到“”或0时,我需要不再禁用国际输入。这可能吗?我的尝试在下面,谢谢

<%= fields.input :line_1, input_html: {class: "uk_input"} %>
<%= fields.input :line_2, input_html: {class: "uk_input"}  %>
<%= fields.input :line_3, input_html: {class: "uk_input"}  %>
<%= fields.input :town, input_html: {class: "uk_input"}  %>
<%= fields.input :county, input_html: {class: "uk_input"}  %>
<%= fields.input :postcode, input_html: {class: "uk_input"}  %>
<%= fields.input :line_1, input_html: {class: "international_input"} %>
<%= fields.input :line_2, input_html: {class: "international_input"} %>
<%= fields.input :line_3, input_html: {class: "international_input"} %>
<%= fields.input :town, label: "City / Region", input_html: {class: "international_input"} %>
<%= fields.input :postcode, label: "Postcode / ZIP Code", input_html: {class: "international_input"} %>

JavaScript

$(document).ready(function() {
  var uk_input = document.querySelector(".uk_input");
  uk_input.onchange = function() {
    if (this.value != "" || this.value.length > 0) {
      international_input = document.querySelectorAll(".international_input")
      international_input.forEach(function(international) {
        international.disabled = true
      })
    }
  }
});

2 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,那么简单而简短的答案是:根据disable的值,将uk_input道具设置为false。

赞:

$(document).ready(function() {
  var uk_input = document.querySelector(".uk_input");
  uk_input.onchange = function() {
    const shouldDisable = this.value != "" || this.value.length > 0;
    international_input = document.querySelectorAll(".international_input")
    international_input.forEach(function(international) {
      international.disabled = shouldDisable;
    })
  }
});

如果您已经在使用jQuery,则可以使用其api:

$(document).ready(function() {
  // bind **all** the inputs change
  $('.uk_input').change(function() {
    // check if any of them has value
    const anyInputHasValue = $('.uk_input').filter((index, item) => !!item.value).length;
    // loop through all the international inputs
    $(".international_input").each(function () {
      // set it prop "disabled" to true if any of the uk inputs has value and vice versa
      $(this).prop('disabled', anyInputHasValue);
    });
  }
});

答案 1 :(得分:0)

您可以执行以下操作:

var uk_input = document.querySelector(".uk_input");
uk_input.onchange = function () {
  international_input =  document.querySelectorAll(".international_input")
  international_input.forEach(function(international) {
    international.disabled = !uk_input.value
  });
}

此操作是每次更改uk_input时都会遍历输入,并根据uk_input是否具有值来禁用/启用它们。