如果复选框被选中,请勾选另一个框。

huangapple go评论55阅读模式
英文:

If checkbox is checked, check another box

问题

I've translated the code part for you:

var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
var chk3 = $("input[type='checkbox'][value='3']");
var chk4 = $("input[type='checkbox'][value='4']");

chk1.on('change', function(){
  chk2.prop('checked', this.checked);
});
chk3.on('change', function(){
  chk2.prop('checked', this.checked);
});
chk4.on('change', function(){
  chk2.prop('checked', this.checked);
});

Please note that I have only translated the code portion, as per your request.

英文:

I'm trying to create a few checkboxes that when checked, will check another... which I got to work! But, the problem I'm having now is that if multiple are selected and one is unchecked at any point, the additional checkbox get unchecked no matter what. I'd like to find a way to have the additional checkbox stay checked, as long as one of the others is, and uncheck if none are selected.

For example: I have 4 checkboxes, if a user selects #1 I want to check #2. Or if a user selects #1 + #3, check #2, but if #3 is unchecked, #2 stays as long as 1,3, or 4 are. I hope this makes sense. I've been trying different things, but this is the code where I landed. Any help, advice on a better way to accomplish this would be greatly appreciated.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var chk1 = $(&quot;input[type=&#39;checkbox&#39;][value=&#39;1&#39;]&quot;);
var chk2 = $(&quot;input[type=&#39;checkbox&#39;][value=&#39;2&#39;]&quot;);
var chk3 = $(&quot;input[type=&#39;checkbox&#39;][value=&#39;3&#39;]&quot;);
var chk4 = $(&quot;input[type=&#39;checkbox&#39;][value=&#39;4&#39;]&quot;);

chk1.on(&#39;change&#39;, function(){
  chk2.prop(&#39;checked&#39;,this.checked);
});
chk3.on(&#39;change&#39;, function(){
  chk2.prop(&#39;checked&#39;,this.checked);
});
chk4.on(&#39;change&#39;, function(){
  chk2.prop(&#39;checked&#39;,this.checked);
});

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;input type=&quot;checkbox&quot; value=&quot;1&quot; class=&quot;user_name&quot;&gt;1
&lt;br&gt;
&lt;input type=&quot;checkbox&quot; value=&quot;2&quot; class=&quot;user_name&quot;&gt;2
&lt;br&gt;
&lt;input type=&quot;checkbox&quot; value=&quot;3&quot; class=&quot;user_name&quot;&gt;3
&lt;br&gt;
&lt;input type=&quot;checkbox&quot; value=&quot;4&quot; class=&quot;user_name&quot;&gt;4

<!-- end snippet -->

答案1

得分: 1

如果您想要在所有其他复选框取消选中之前保持 chk2 处于选中状态,您需要在每个事件处理程序中查找所有其他复选框的状态。理想情况下,您应该创建一个函数来执行此操作,以便不必为所有处理程序重复相同的代码。

function toggleChk2() {
  let check2 = (chk1.is(':checked') ||
      chk3.is(':checked') ||
      chk4.is(':checked'))
  chk2.prop('checked', check2);
}

chk1.on('change', function(){
  toggleChk2();
});
chk2.on('change', function(){
  toggleChk2();
});
chk3.on('change', function(){
  toggleChk2();
});
chk4.on('change', function(){
  toggleChk2();
});

如果您还想防止手动更改该复选框,还可以将此函数添加到 chk2 的更改处理程序中。

英文:

If you want to keep chk2 checked until all others are unchecked, you have to look for the status of all other boxes in each event handler. Ideally, you would create a function for that, so you don't need to repeat your code for all handlers.

function toggleChk2() {
  let check2 = (chk1.is(&#39;:checked&#39;) ||
      chk3.is(&#39;:checked&#39;) ||
      chk4.is(&#39;:checked&#39;))
  chk2.prop(&#39;checked&#39;,check2);
}

chk1.on(&#39;change&#39;, function(){
  toggleChk2();
});
chk2.on(&#39;change&#39;, function(){
  toggleChk2();
});
chk3.on(&#39;change&#39;, function(){
  toggleChk2();
});
chk4.on(&#39;change&#39;, function(){
  toggleChk2();
});

You can also add this function to the change handler of chk2 if you want to prevent manual change of that checkbox.

答案2

得分: 1

以下是您要翻译的内容:

For the record: alternative without JQuery, using event delegation and a css selector to query the state of the other checkboxes:

[change, click].forEach( evtType =>
document.addEventListener(evtType, handle) );

function handle(evt) {
if (evt.target.closest(.user_name)) {
const cb2 = document.querySelector(.user_name[value="2"]);
const oneOfOthersChecked =
document.querySelector(.user_name:not([value="2"]):is(:checked));
return cb2.checked = !!oneOfOthersChecked || cb2.checked;
}
if (evt.target.id === "empty") {
return document.querySelectorAll(.user_name:checked)
.forEach(cb => cb.checked = !cb.checked);
}
return true;
}

<!-- language: lang-html -->

1

2

3

4

请注意,代码部分没有翻译。

英文:

For the record: alternative without JQuery, using event delegation and a css selector to query the state of the other checkboxes:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

[`change`, `click`].forEach( evtType =&gt; 
  document.addEventListener(evtType, handle) );

function handle(evt) {
  if (evt.target.closest(`.user_name`)) {
    const cb2 = document.querySelector(`.user_name[value=&quot;2&quot;]`);
    const oneOfOthersChecked = 
      document.querySelector(`.user_name:not([value=&quot;2&quot;]):is(:checked)`);
    return cb2.checked = !!oneOfOthersChecked || cb2.checked;
  }
  if (evt.target.id === &quot;empty&quot;) {
    return document.querySelectorAll(`.user_name:checked`)
      .forEach(cb =&gt; cb.checked = !cb.checked);
  }
  return true;
}

<!-- language: lang-html -->

&lt;input type=&quot;checkbox&quot; value=&quot;1&quot; class=&quot;user_name&quot;&gt;1
&lt;br&gt;
&lt;input type=&quot;checkbox&quot; value=&quot;2&quot; class=&quot;user_name&quot;&gt;2
&lt;br&gt;
&lt;input type=&quot;checkbox&quot; value=&quot;3&quot; class=&quot;user_name&quot;&gt;3
&lt;br&gt;
&lt;input type=&quot;checkbox&quot; value=&quot;4&quot; class=&quot;user_name&quot;&gt;4
&lt;br&gt;
&lt;button id=&quot;empty&quot;&gt;Uncheck all&lt;/button&gt;

<!-- end snippet -->

答案3

得分: 0

这个结构可能有点过于复杂,但你可以在一个结构内定义“dependencies”(依赖关系)。

// 使用对象表示法显示的映射内容
const dependenciesOf = Map{
  "chk1": ["chk2"],
  "chk3": ["chk2"],
  "chk4": ["chk2"],
  "chk5": ["chk1", "chk4"]
}

有了这个定义的结构,我们可以编写一个程序来构建一个反向索引。

// 使用对象表示法显示的映射内容
const requiredBy = Map{
  "chk1": ["chk5"],
  "chk2": ["chk1", "chk3", "chk4"],
  "chk4": ["chk5"]
}

有了这两个结构的定义,我们可以使用以下的 change 事件处理程序:

$('input[type="checkbox"]').on("change", function () {
  const dependencies = dependenciesOf.get(this.id) || [];
  for (const dependency of dependencies) {
    if (this.checked) {
      // 标记依赖项为已选中并禁用交互
      $(`#${dependency}`).prop("disabled", true).prop("checked", true).trigger("change");
    } else {
      // 当不再需要依赖项时,启用依赖项交互
      const ids = requiredBy.get(dependency) || [];
      const isRequired = ids.some(id => $(`#${id}`).prop("checked"));
      if (!isRequired) $(`#${dependency}`).prop("disabled", false);
    }
  }
});

这将标记所有相关的依赖项为“已选中”,并在另一个复选框需要它时禁用用户交互。我们在更改“已选中”值后使用 .trigger("change") 来递归检查依赖项。如果不这样做,chk5 只会检查 chk1chk4,但不会检查 chk2

英文:

This might be a bit overkill, but you could define the "dependencies" inside a structure.

// Map contents displayed using object notation
const dependenciesOf = Map{
  &quot;chk1&quot;: [&quot;chk2&quot;],
  &quot;chk3&quot;: [&quot;chk2&quot;],
  &quot;chk4&quot;: [&quot;chk2&quot;],
  &quot;chk5&quot;: [&quot;chk1&quot;, &quot;chk4&quot;]
}

With this structure defined we can programmatically build a reverse index.

// Map contents displayed using object notation
const requiredBy = Map{
  &quot;chk1&quot;: [&quot;chk5&quot;],
  &quot;chk2&quot;: [&quot;chk1&quot;, &quot;chk3&quot;, &quot;chk4&quot;],
  &quot;chk4&quot;: [&quot;chk5&quot;]
}

With these 2 structures defined we can use the following change event handler:

$(&#39;input[type=&quot;checkbox&quot;]&#39;).on(&quot;change&quot;, function () {
  const dependencies = dependenciesOf.get(this.id) || [];
  for (const dependency of dependencies) {
    if (this.checked) {
      // mark the dependency as checked and disable interaction
      $(`#${dependency}`).prop(&quot;disabled&quot;, true).prop(&quot;checked&quot;, true).trigger(&quot;change&quot;);
    } else {
      // enable the dependency interaction whenever the dependency is no longer required
      const ids = requiredBy.get(dependency) || [];
      const isRequired = ids.some(id =&gt; $(`#${id}`).prop(&quot;checked&quot;));
      if (!isRequired) $(`#${dependency}`).prop(&quot;disabled&quot;, false);
    }
  }
});

This will mark all the relevant dependencies as checked and will disable the user interaction as long as it's required by another checkbox.

The reason we .trigger(&quot;change&quot;) after changing the checked value, is to recursively check dependencies. If we don't do this chk5 would only check chk1 and chk4, but not chk2.

<!-- begin snippet: js hide: true console: true babel: false -->

<!-- language: lang-js -->

// define dependencies (based on element ID)
const dependenciesOf = new Map([
  [&quot;chk1&quot;, [&quot;chk2&quot;]], // checkbox 1 requires checkbox 2 to be set
  [&quot;chk3&quot;, [&quot;chk2&quot;]], // checkbox 3 requires checkbox 2 to be set
  [&quot;chk4&quot;, [&quot;chk2&quot;]], // checkbox 4 requires checkbox 2 to be set
  [&quot;chk5&quot;, [&quot;chk1&quot;, &quot;chk4&quot;]], // checkbox 5 requires checkbox 1 and 4 to be set
]);

// programatically build a reverse index of the dependencies
const requiredBy = new Map();
for (const [checkbox, dependencies] of dependenciesOf) {
  for (const dependency of dependencies) {
    if (!requiredBy.has(dependency)) requiredBy.set(dependency, []);
    requiredBy.get(dependency).push(checkbox);
  }
}

$(&#39;input[type=&quot;checkbox&quot;]&#39;).on(&quot;change&quot;, function () {
  const dependencies = dependenciesOf.get(this.id) || [];
  for (const dependency of dependencies) {
    if (this.checked) {
      // mark the dependency as checked and disable interaction
      $(`#${dependency}`).prop(&quot;disabled&quot;, true).prop(&quot;checked&quot;, true).trigger(&quot;change&quot;);
    } else {
      // enable the dependency interaction whenever the dependency is no longer required
      const ids = requiredBy.get(dependency) || [];
      const isRequired = ids.some(id =&gt; $(`#${id}`).prop(&quot;checked&quot;));
      if (!isRequired) $(`#${dependency}`).prop(&quot;disabled&quot;, false);
    }
  }
});

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;input id=&quot;chk1&quot; type=&quot;checkbox&quot; value=&quot;1&quot; /&gt;&lt;label for=&quot;chk1&quot;&gt;1&lt;/label&gt;&lt;br /&gt;
&lt;input id=&quot;chk2&quot; type=&quot;checkbox&quot; value=&quot;2&quot; /&gt;&lt;label for=&quot;chk2&quot;&gt;2&lt;/label&gt;&lt;br /&gt;
&lt;input id=&quot;chk3&quot; type=&quot;checkbox&quot; value=&quot;3&quot; /&gt;&lt;label for=&quot;chk3&quot;&gt;3&lt;/label&gt;&lt;br /&gt;
&lt;input id=&quot;chk4&quot; type=&quot;checkbox&quot; value=&quot;4&quot; /&gt;&lt;label for=&quot;chk4&quot;&gt;4&lt;/label&gt;&lt;br /&gt;
&lt;input id=&quot;chk5&quot; type=&quot;checkbox&quot; value=&quot;5&quot; /&gt;&lt;label for=&quot;chk5&quot;&gt;5&lt;/label&gt;&lt;br /&gt;

<!-- end snippet -->

I don't know if this is the answer you're looking for, but I hope this gives you at least some inspiration.

huangapple
  • 本文由 发表于 2023年5月15日 14:50:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76251511.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定