0

I am trying to display multiple checkbox values in a separate DIV to show the results of the checkboxes to the user. But I also want to remove the value if the user de-selects the checkbox. This is the code I have so far but can only display/hide one value at a time. For example, if I click checkboxes a, b, and c, it will show all values. But If I uncheck, they will hide. Thanks

<input onchange="selectArr(this)" type="checkbox" name="accessory" value="a"/>
<input onchange="selectArr(this)" type="checkbox" name="accessory" value="b"/>
<input onchange="selectArr(this)" type="checkbox" name="accessory" value="c"/>


<div id="acc"></div>
    
function selectAcc(cb) {
    var x = cb.checked ? cb.value : '';
    document.getElementById("acc").innerHTML = x;
}
DreamBold
  • 2,727
  • 1
  • 9
  • 24
frankieseattle
  • 161
  • 1
  • 10
  • Inline event handlers like `onchange` are [bad practice](/q/11737873/4642212). They’re an [obsolete, cumbersome, and unintuitive](/a/43459991/4642212) way to listen for events. Always [use `addEventListener`](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. Use [event delegation](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of adding several event listeners — it’s more maintainable and applies to dynamically added elements. – Sebastian Simon Nov 26 '22 at 01:30
  • See [the tag info](/tags/event-delegation/info) and [this Q&A](/a/55452921/4642212). Use the [event argument](//developer.mozilla.org/en/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback): `addEventListener("change", ({`[`target`](//developer.mozilla.org/en/docs/Web/API/Event/target)`}) => { const checkbox = target.closest("[name=accessory]"); if(checkbox){ document.getElementById("acc").textContent = Array.from(document.querySelectorAll("[name=accessory]:checked")).map(({ value }) => value).join(", "); } });`. – Sebastian Simon Nov 26 '22 at 01:32
  • As far as I understand, you want to show all the checked values in the div, correct? – DreamBold Nov 26 '22 at 01:53

3 Answers3

1

// selecting input type checkboxes
const inputCheckBoxes = document.querySelectorAll("input[type=checkbox]");
const main = document.querySelector("#main");
// function to print in main div
const printCheckedValue = (array) => {
  main.innerText = "";
  array.forEach(value => {
    main.innerText += value;
  })
}
// to store checkboxed values
let checkedValue = [];
// looping through all inputcheckboxes and attching onchange event
Object.values(inputCheckBoxes).forEach((inputCheckBoxe, index) => {
  inputCheckBoxe.onchange = (e) => {
  // checking if value is checkedbox or not
    if (checkedValue.includes(e.target.value)) {
    // if checkeboxed than filtering array
      checkedValue = checkedValue.filter(val => val != e.target.value)
      printCheckedValue(checkedValue);
    } else {
      checkedValue.push(e.target.value);
      printCheckedValue(checkedValue);
    }
  }
})
<input type="checkbox" name="accessory" value="a" />
<input type="checkbox" name="accessory" value="b" />
<input type="checkbox" name="accessory" value="c" />


<div id="main"></div>
Nexo
  • 2,125
  • 2
  • 10
  • 20
0

Try put like something this

var checked = []

function selectAcc(cb) {
    if(cb.checked){
        checked.push(cb.value)
    } else {
        var index = checked.indexOf(cb.value)
        checked.splice(index, 1)
}
    document.getElementById("acc").innerHTML = checked.join(' ');
}
0

Hope this works for you .

function selectAcc(cb) {
        // get previous div value
        var previousValue = document.getElementById("acc").getAttribute('value');
        var newValue = previousValue;
        //store the new clicked value
        var value = cb.value;
        // if the new value is checked and the value is not present in the div add it to the div string value
        if (cb.checked && !previousValue.includes(value)) newValue+=value ;
        // else remove the value from div string value
        else previousValue = newValue.replace(value, '');
        // update new value in div
        document.getElementById("acc").innerHTML = newValue;
    }
Tarmah
  • 139
  • 6