0

I would like to get dynamically in an array all of the checked checkboxes every time the user clicks on one of them using Jquery or javascript. PS: I'm using Django + Python to generate the options and Bootstrap to style them Here is my code :

{% for option in options %}
    <div class="input-group" style="margin-bottom: 7px;">
        <div class="input-group-prepend">
            <div class="input-group-text">
                <input type="checkbox" name="checks[]" aria-label="Radio button for following text input" id="option_choice" class="ipad_pro" value="{{ option.name }}" onclick="getCheckedCheckboxes('option_choice')">
            </div>
        </div>
        <input style="background-color: #fff;" type="text" class="form-control" disabled=True value="{{ option.name }} {{ option.price }}€" aria-label="Text input with radio button">
    </div>
{% endfor %}

So far, I've tried to do it like this :

function getCheckedBoxes(chkboxId) {
  var checkboxes = document.querySelectorAll('#' + chkboxId);
  var checkboxesChecked = [];
  for (var i=0; i<checkboxes.length; i++) {
     if (checkboxes[i].checked) {
        checkboxesChecked.push(checkboxes[i]);
     }
  }
  return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
var checkedBoxes = getCheckedBoxes("option_choice");

But that hasn't worked out for me.

Please help me if you know the answer to my problem.

Fantasmo Clone27
  • 333
  • 1
  • 10
  • 19
  • 1
    Possible duplicate of [Does ID have to be unique in the whole page?](https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page) – Taplar Jul 27 '18 at 21:56
  • You can get all checked checkboxes using `$("[type='checkbox']:checked")`. But `id`s **do** need to be unique, as pointed above. – tao Jul 27 '18 at 22:03
  • `:checked` is also a valid css selector and works with `querySelectorAll`. http://jsfiddle.net/0srez4L5/2/ – Taplar Jul 27 '18 at 22:04
  • uses self-defined attribute may be one option, like ``, then query like `$("[data-fantasmo-id='option_choice']:checked")` – Sphinx Jul 27 '18 at 22:04
  • @Taplar, regarding your remark above, `querySelectorAll` [actually works](https://jsfiddle.net/websiter/xjcmd8w0/) with duplicated ids. Which doesn't make them legal, but that is not the issue here. The issue is OP is checking the `checked` property, which doesn't get updated by browser when a checkbox is checked/unchecked. It only sets the initial value of the checkbox when the element is rendered. – tao Jul 27 '18 at 22:09
  • @AndreiGheorghiu woah, I forgot about that weirdness. Removed comment. Modified => You should not repeat ids. It is invalid by web standards. – Taplar Jul 27 '18 at 22:11
  • @Taplar, it's not that weird, if you think about it. If this wasn't technically possible, how could you programatically correct a bunch of code with duplicated ids? :D – tao Jul 27 '18 at 22:12
  • In a perfect world, you wouldn't be able to repeat *unique* ids. ^_^ But, backwards compatibility is a thing.... – Taplar Jul 27 '18 at 22:13
  • @Andrei Gheorghiu 'duplicated id error' is browser based, though chrome and firefox may work fine now for duplicated id, but in future may not, and other browser may not now. – Sphinx Jul 27 '18 at 22:14
  • @Sphinx so you're saying `.querySelectorAll()` returns different results in different browsers? I thought it's pretty standard and works the same in all browsers. – tao Jul 27 '18 at 22:15
  • @AndreiGheorghiu check [Two HTML elements with same id attribute: How bad is it really?](https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really) – Sphinx Jul 27 '18 at 22:19
  • 1
    http://jsfiddle.net/ozxw0prt/4/ Actually this logic works fine. The issue is the inline onclick binding is not the same name as the global method name. @AndreiGheorghiu – Taplar Jul 27 '18 at 22:20
  • Good find, @Taplar. – tao Jul 27 '18 at 22:20
  • @AndreiGheorghiu if the browser can't handle one html with duplicated id (like fail to build dom tree), then `.querySelectorAll` will not work. – Sphinx Jul 27 '18 at 22:22
  • I'm not sure I understand what you mean by *"if browser can't handle one html with duplicated id"*, @Sphinx. Feel free to use technical terms. I'm not exactly what you'd call a rookie. Please give me an example of a browser which *"can't handle one html with duplicated id"* and also give me an example of a browser which doesn't return all elements with same ID when using `document.querySelectorAll()` – tao Jul 27 '18 at 22:26
  • I think he's suggesting that it may not work the same in all browsers, so relying on it is not a good thing. Speculation on my part though. – Taplar Jul 27 '18 at 22:28
  • My understanding of *"not being able to handle"* is probably different. For me it equates to: browser can not handle (crashes or freezes), page no longer works, user eventually loses their mind and out the window goes the monitor, killing the neighbor's dog. By comparison, I'd say most browsers handle duplicate IDs fairly well. They don't even issue a console warning. Sometimes I wish they did. – tao Jul 27 '18 at 22:45

3 Answers3

5

to get all checked checkbox inputs using JS:

var checked = document.querySelectorAll("input[type=checkbox]:checked");

Olaf Erlandsen
  • 5,817
  • 9
  • 41
  • 73
hcas
  • 93
  • 7
2

Jquery $('input[type=checkbox]:checked')

Using the :checked selector

https://api.jquery.com/checked-selector/

Arif
  • 308
  • 2
  • 8
1
<input type="checkbox" name="checks[]" aria-label="Radio button for following text input" id="option_choice" class="ipad_pro" value="{{ option.name }}"
       onclick="getCheckedCheckboxes('option_choice')">

You are trying to bind a click handler on the getCheckedCheckboxes method, but your function name is getCheckedBoxes, so clicking the element isn't going to run that method.

Taplar
  • 24,788
  • 4
  • 22
  • 35