-1

I need a drop-down with check-boxes but without using the select feature as I want to check multiple checkbox at once (I don't want the multiple on select).

I have tried adding classes to the checkbox and then check via jQuery or via vanilla Javascript if they're 'checked' but I never get an answer.

How I'm checking in jQuery -

if($('.apple').is(':checked')){
    alert('I WAS CLICKED')
}

How I'm checking with JS -

let apple = document.getElementByClassName('apple')

if(apple.checked){
  alert('I WAS CLICKED')
}

This is the fiddle: http://jsfiddle.net/8L4g5dov/3/

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
MCM13
  • 237
  • 1
  • 4
  • 12
  • Possible duplicate of [How to check whether a checkbox is checked in jQuery?](https://stackoverflow.com/questions/901712/how-to-check-whether-a-checkbox-is-checked-in-jquery) – Nidhin Joseph Aug 12 '19 at 02:28
  • you need to listen to an event. – Daniel A. White Aug 12 '19 at 02:29
  • https://www.google.com/amp/s/www.jquery-az.com/7-demos-of-jquery-multi-select-dropdown-with-checkboxes-plug-in/amp/ – estinamir Aug 12 '19 at 02:32
  • Possible duplicate of [Check if checkbox is checked with jQuery](https://stackoverflow.com/questions/2204250/check-if-checkbox-is-checked-with-jquery) – LoicTheAztec Aug 20 '19 at 10:55

2 Answers2

1

Your current code only determines whether a checkbox was checked at the point it runs. You need to listen for an event on the checkbox and respond to it instead.

jQuery:

$('.apple').change(function() {
    if ($(this).is(':checked')) {
        alert('I WAS CHECKED');
    }
});

Vanilla JS:

let checkboxNodes = document.getElementByClassName('apple');
let checkboxArray = Array.from(checkboxNodes); // ways to shorten but here for clarity.

function respondToCheck() {
    if (this.checked) {
        alert('I WAS CLICKED');
    }
}

checkboxArray.forEach(el => el.addEventListener('change', respondToCheck));
Nathan Dawson
  • 18,138
  • 3
  • 52
  • 58
1

I checked your fiddle an the solution i came across was this:

 items.addEventListener('click', function(){
   $('input[type=checkbox]:checked').each(function () {
    console.log($(this).parent('li').text())
   }) 
 })

Hope it helps

Japsz
  • 785
  • 6
  • 14