Each checkbox appears twice

Setting:

  • jQuery 3.2.1
  • Semantic interface 2.1
  • Chrome

HTML (based on https://semantic-ui.com/modules/checkbox.html#/definition ):

<div id="checkboxes">
    <div class="ui checkbox">
        <input type="checkbox" name="checkboxes" value="checkbox1">
        <label>Branch</label>
    </div>
    <div class="ui checkbox">
        <input type="checkbox" name="checkboxes" value="checkbox2">
        <label>Branch</label>
    </div>
    <div class="ui checkbox">
        <input type="checkbox" name="checkboxes" value="checkbox3">
        <label>Branch</label>
    </div>
    ...
</div>

      

* They are all initially verified. ** User disables the ones they want to deactivate.

In my JS file, I am using the following function to check which checkboxes are checked:

$('input:checkbox[name=checkboxes]:checked').each(function () {
        // Do something with them
    });

      

However, each checkbox is displayed twice (once in a new state - checked or unchecked, and once in its original state - all checked). This confuses my logic after that, making the tick pointless.

I went into Chrome Developer Tools and used the same selector in the console. Got this back:

input#checkbox2, input#checkbox3, input#checkbox1, input#checkbox2, input#checkbox3

(I unchecked the box checkbox1

)

Any ideas on why it will show up twice, or what I'm missing here?

+3


source to share


2 answers


So after a lot of beating, it turned out that the problem is. My answer is here, for posterity:

It is a byproduct of using semantics / way of making semantics

Cause

These checkboxes were modal. When Semantic initializes a modal, it creates a copy of all elements and appends them to the end of the DOM.

^ This results in two copies appearing as in my problem.

Searching by ID will use the last copy of the DOM element with that ID; any changes I make (check / re-check) will happen on the copy, not the original.



Note : This is also true for semantic dropdowns inside modals.

Decision

Put your checkboxes (or dropdowns) in div

and give it an id like my source code.

<div id="my_checkboxes">
    <div class="ui checkbox">
        <input type="checkbox" name="checkboxes" value="checkbox1">
        <label>Branch</label>
    </div>
</div>

      

However, instead of referring to them with input

and name

refer to them using this parent div

:

$('#my_checkboxes').children().each(function() {
    // do something
});

      

0


source


You can use below method to check the checked boxes



$('#checkboxes input:checked').each(function () {
   console.log($(this))
 });

      

+1


source







All Articles