英文:
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 = $("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);
});
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="1" class="user_name">1
<br>
<input type="checkbox" value="2" class="user_name">2
<br>
<input type="checkbox" value="3" class="user_name">3
<br>
<input type="checkbox" value="4" class="user_name">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(':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();
});
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 =>
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 -->
<input type="checkbox" value="1" class="user_name">1
<br>
<input type="checkbox" value="2" class="user_name">2
<br>
<input type="checkbox" value="3" class="user_name">3
<br>
<input type="checkbox" value="4" class="user_name">4
<br>
<button id="empty">Uncheck all</button>
<!-- 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
只会检查 chk1
和 chk4
,但不会检查 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{
"chk1": ["chk2"],
"chk3": ["chk2"],
"chk4": ["chk2"],
"chk5": ["chk1", "chk4"]
}
With this structure defined we can programmatically build a reverse index.
// Map contents displayed using object notation
const requiredBy = Map{
"chk1": ["chk5"],
"chk2": ["chk1", "chk3", "chk4"],
"chk4": ["chk5"]
}
With these 2 structures defined we can use the following change
event handler:
$('input[type="checkbox"]').on("change", 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("disabled", true).prop("checked", true).trigger("change");
} else {
// enable the dependency interaction whenever the dependency is no longer required
const ids = requiredBy.get(dependency) || [];
const isRequired = ids.some(id => $(`#${id}`).prop("checked"));
if (!isRequired) $(`#${dependency}`).prop("disabled", 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("change")
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([
["chk1", ["chk2"]], // checkbox 1 requires checkbox 2 to be set
["chk3", ["chk2"]], // checkbox 3 requires checkbox 2 to be set
["chk4", ["chk2"]], // checkbox 4 requires checkbox 2 to be set
["chk5", ["chk1", "chk4"]], // 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);
}
}
$('input[type="checkbox"]').on("change", 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("disabled", true).prop("checked", true).trigger("change");
} else {
// enable the dependency interaction whenever the dependency is no longer required
const ids = requiredBy.get(dependency) || [];
const isRequired = ids.some(id => $(`#${id}`).prop("checked"));
if (!isRequired) $(`#${dependency}`).prop("disabled", false);
}
}
});
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="chk1" type="checkbox" value="1" /><label for="chk1">1</label><br />
<input id="chk2" type="checkbox" value="2" /><label for="chk2">2</label><br />
<input id="chk3" type="checkbox" value="3" /><label for="chk3">3</label><br />
<input id="chk4" type="checkbox" value="4" /><label for="chk4">4</label><br />
<input id="chk5" type="checkbox" value="5" /><label for="chk5">5</label><br />
<!-- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论