Copy Selected Checkbox Value From One Checkbox To Another Immediately Using JQUERY

本秂侑毒 提交于 2019-12-24 12:12:56

问题


I'm relatively new to Jquery and have been struggling with this problem for the last day or so. I am trying to do something seemingly simple, but I can't quite work it out. I have two identical checkboxes with many entries and multiple choices can be selected by the end user in either checkbox. If a value in checkboxa is selected, I want it to immediately select the identical value in the checkboxb. I have researched many solutions, and I have tried the following:

       $(document).ready(function (){
       $("#id_checkboxa").change(function() {
         $('#id_checkboxa input[type="checkbox"]:checked').each(function(){
             $('#id_checkboxb input[type="checkbox"]').eq($(this).index()).prop('checked',true);
         });
       });
      });

My HTML. I'm using Django template and forms with a queryset for the choices, which is why I am trying to leverage the ID via Jquery for checkbox manipulation.

<div class="spacer34">
  <label class="title130">Checkboxa:</label>
    <div class="spacer68">
      <div class="spacer73">
        {{ form.checkboxa }}
      </div>
    </div>
</div>

I found the approach above by referencing the following code snippet on SO..Copy check state of a set of checkboxes to another fieldset

The above will copy the first value I select in checkboxa to the top of the checkboxb, but that's it. I suspect I need to loop through the index or create an array to try and find the checked values, but can't quite work it out. I definitely want to use the JQUERY ID approach in solving this problem. Thanks in advance for any thoughts.

After experimenting, I have gotten as far as...

            $(document).ready(function (){
            $("#id_checkboxa").change(function() {
                console.log("Hello world!");            
             });
             });

And my console will show the hello world!

When I try to do something like...

            $(document).ready(function (){
            $("#id_checkboxa").change(function() {
                console.log("Hello world!");
                let selectedValA = $(this).val();
                let isAChecked = $(this).prop("checked");
                $(`#id_checkboxb[value=${selectedValA}]`).prop("checked", isAChecked);
             });
             });

I get the following error:

jquery.min.js:2 Uncaught Error: Syntax error, unrecognized expression: #id_checkboxb[value=]
    at Function.fb.error (jquery.min.js:2)
    at fb.tokenize (jquery.min.js:2)
    at fb.select (jquery.min.js:2)
    at Function.fb [as find] (jquery.min.js:2)
    at n.fn.init.find (jquery.min.js:2)
    at new n.fn.init (jquery.min.js:2)
    at n (jquery.min.js:2)
    at HTMLUListElement.<anonymous> ((index):85)
    at HTMLUListElement.dispatch (jquery.min.js:3)
    at HTMLUListElement.r.handle (jquery.min.js:3)

I know from prior experimentation that Django forms and JQuery can be a challenge to connect just right at times. Thanks in advance for any other thoughts.

If I do the following...

              $(document).ready(function (){
              $("#id_checkboxa").change(function() {
                  console.log("Hello world!");
                  let selectedValA = $(this).val();
                  let isAChecked = $(this).prop("checked");
                    $('#id_checkboxb input[type=checkbox]').prop('checked', true);
               });
               });

The minute I select a checkbox value in checkboxa, all of checkboxb values get selected. I am trying to just get the value I selected in checkboxa to appear n checkboxb, not all checkboxes.


回答1:


I believe I know what you are trying to do. This seems like it could be easier with classes (group the checkboxes by class names)

When a checkbox with checkboxA class is clicked it will also check the checkbox with class checkboxB and only if it also has the same value as checkboxA

$(document).ready(function() {
  $(".checkboxA").change(function() {
    let selectedValA = $(this).val();
    let isAChecked = $(this).prop("checked");
    // get a checkbox from the checkboxs with class "checkboxB" and have the same value as the checked checkboxA and set its checked prop to the same as checkboxA
    $(`.checkboxB[value=${selectedValA}]`).prop("checked", isAChecked);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- checkbox set A -->
<div>
one <input type="checkbox" class="checkboxA" value="1"/>
two <input type="checkbox" class="checkboxA" value="2"/>
three <input type="checkbox" class="checkboxA" value="3"/>
four <input type="checkbox" class="checkboxA" value="4"/>
five <input type="checkbox" class="checkboxA" value="5"/>
</div>

<br/>
<br/>

<!-- checkbox set B -->
<div>
one <input type="checkbox" class="checkboxB" value="1"/>
two <input type="checkbox" class="checkboxB" value="2"/>
three <input type="checkbox" class="checkboxB" value="3"/>
four <input type="checkbox" class="checkboxB" value="4"/>
five <input type="checkbox" class="checkboxB" value="5"/>
</div>



回答2:


Can't you simply toggle all boxes of same class that are not the selected checkbox?

$('.CbAB').off('change').on('change', function() {
  $('.CbAB').not(this).prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class="CbAB" type="checkbox" name="CB" value="A">A<br>
<input class="CbAB" type="checkbox" name="CB" value="B">B<br>



回答3:


Since I'm using Django forms and templates, I could not easily use class. Leveraging the suggestions above along with a ton of research. I found that I needed to use the input name and not the class or ID. Here is my code that solved my problem.

        $(document).ready(function() {
          $("[name=checkboxa]").change(function() {
            let selectedValA = $(this).val();
            let isAChecked = $(this).prop("checked");
            $(`[name=checkboxb][value="${selectedValA}"]`).prop("checked", isAChecked);
          });
        });
        });

You need to interrogate your DOM and figure out what the name of the checkboxes is. In the case above, the name was checkboxa and checkboxb. Thanks for all of the suggestions that helped get me here.



来源:https://stackoverflow.com/questions/52539570/copy-selected-checkbox-value-from-one-checkbox-to-another-immediately-using-jque

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!