I want to determine what is being checked in multiple check boxes.

Asked 1 years ago, Updated 1 years ago, 337 views

Ideally, if 1 is checked, the console log displays "1 checked."
When 1 and 3 are checked, the console log displays "1 and 3 checked."
Once 1 and 2 and 3 are checked, I would like to make a check decision like "1 and 2 and 3 have been checked" in the console log.

I gave one, two, and three as an example, but these are from one to eight.
I'd like to shorten the code, but please let me know if you know!

function sample1(checked){
  if(checked){} else{}
}

function sample2(checked){
  if(checked){} else{}
}

function sample3(checked){
  if(checked){} else{}
}
<div>
  <label><input type="checkbox" onchange="sample1(this.checked)">1</label>
</div>
<div>
  <label><input type="checkbox" onchange="sample2(this.checked)">2</label>
</div>
<div>
  <label><input type="checkbox" onchange="sample3(this.checked)">3</label>
</div>

javascript

2022-09-30 21:53

1 Answers

Since the checked property is specified as the argument for the onChange event in the sample question, it would be good to rewrite it to specify the CheckBox itself.

onchange="sample1(this.checked)"onchange="sample(this)"

By the way, the purpose of this time is to extract (*1) the selected check box from all HTML check boxes, and (*2) combine the text of the parent element label like ~to ~ga.

Techniques such as queries (*1) and filters (*2), maps, and joiners (*3) are often used, not just for shortening the code.
For your information, go ahead.

function sample(checkbox){
    // check the status of checked controls
    if(!checkbox.checked)return;

    // Determine what is checked in multiple check boxes ( 11- の3)
    // US>From all HTML checkboxes
    let checks = document.querySelectorAll("input[type='checkbox']");
    // Extract the selected check box.
    let filtered=[].slice.call(checks).filter(c=>c.checked);
    // Combine parent element 'label' text like '~ and ~ga'
    lets=filtered.map(c=>c.parentElement.textContent).join(' and ');
    console.log(s+') checked.');
}
<div>
<label><input type="checkbox" name="check1"
onchange="sample(this)">1</label>
</div>
<div>
<label><input type="checkbox" name="check2"
onchange="sample(this)">2</label>
</div>
<div>
<label><input type="checkbox" name="check3"
onchange="sample(this)">3</label>
</div>


2022-09-30 21:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.