1

I need to get a list of the checkbox values when checked and passed them to an input. However, my value is duplicated when I click checkall first. Please help me. Thanks.

My Code

<input id="listvalue" name="selectedCB">
<input type="checkbox" onclick="toggle(this)" name="checkedAll" id="checkedAll" />
<div class="tycheck">
  <input type="checkbox" name="checkAll" value="2" class="checkSingle" />
  <input type="checkbox" name="checkAll" value="1" class="checkSingle" />
  <input type="checkbox" name="checkAll" value="3" class="checkSingle" />
</div>

$(document).ready(displayCheckbox);
    var idsArr = [];
    var displayField = $('input[name=selectedCB]');
    function toggle(source) {                    
        var checkboxes = document.querySelectorAll('.tycheck input[type="checkbox"]');
        for (var i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i] != source)
                checkboxes[i].checked = source.checked;
            idsArr = [];
            $('#checkall').find('input[type=checkbox]:checked').each(function () {
                idsArr.push(this.value);
            });
            displayField.val(idsArr);                
        }
    }
    function displayCheckbox() {
        var checkboxes = $(".tycheck input[type=checkbox]");
        function printChecked() {
            var checkedIds = [];
            idsArr = [];
            // for each checked checkbox, add it's id to the array of checked ids
            checkboxes.each(function () {
                if ($(this).is(':checked')) {
                    idsArr.push($(this).attr('value'));
                    console.log(idsArr);
                }
                else {
                    var checkboxesallcheck = document.querySelectorAll('input[name="checkedAll"]');
                    for (var j = 0; j < checkboxesallcheck.length; j++) {
                        checkboxesallcheck[j].checked = false;

                    }
                }
                displayField.val(idsArr);
            });

        }
        $.each(checkboxes, function () {
            $(this).change(printChecked);
        })
    }

How to get a list of the checkbox values when checked and passed them to an input. :(

1
  • @Andreas Thank you for taking the time to help. However, I still don't understand what you mean, you can say it more clearly. Thank you Commented Jan 8, 2020 at 10:43

2 Answers 2

1

You can try this:

var idsArr = [];
var displayField = $('input[name=selectedCB]');
var checkboxes = Array.from($(".tycheck input[type=checkbox]"));

function toggle(source) {
    var values = checkboxes.map(x => {
      x.checked = source.checked;

      return source.checked ? x.value : '';
    }).join(source.checked ? ',' : '');
      
    displayField.val(values);
}

function printChecked() {
    var values = checkboxes.filter(x => x.checked).map(x => x.value);

    displayField.val(values);
}

$.each(checkboxes, function () {
    $(this).change(printChecked);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<input id="listvalue" name="selectedCB">
<input type="checkbox" onclick="toggle(this)" name="checkedAll" id="checkedAll" />
<div class="tycheck">
  <input type="checkbox" name="checkAll" value="2" class="checkSingle" />
  <input type="checkbox" name="checkAll" value="1" class="checkSingle" />
  <input type="checkbox" name="checkAll" value="3" class="checkSingle" />
</div>

Sign up to request clarification or add additional context in comments.

5 Comments

For my suggestion don't over use loops for same arr. filter().map() for small case is good.For big array its run all the arguments 2 times.for this case jquery default have elem.map concept .Use such a map avoid unnecessary array conversion
Tks guys, happy
Hi, @Tân Thank you for the help, but it didn't work when activating buttons: ['colvis'] in DataTable, I searched for solutions on the Internet, but it didn't seem to work.
@ChimDiTru So, how does it relate to your question above?
I'm sorry, I created a new question here: stackoverflow.com/questions/59657456/…. Look forward to your help. Tks
0

You could do like this

  1. Use any one of the type javascript selector or JQuery selector
  2. Not necessary to use Array or forloops .All function already there in jquery concept .For that we used Jquery.map
  3. For below i have simply create one change function call.checker
  4. Then call that function on checkbox change event in both checkall and normal check event

$(document).ready(function() {
  const elem = $('.tycheck input[type=checkbox]'); //select the checkbox elem
  elem.on('change', function() {
    checker(elem) //get the checked value list
  })
  $('#checkedAll').on('change', function() {
    elem.prop('checked', $(this).is(':checked')) //for select all simply compare with checkall button
    checker(elem)
  })
})


function checker(elem) {
  let res = elem.map((i, item) => {
    if ($(item).is(':checked')) {
      return $(item).val()
    }
  }).get()
  $('#listvalue').val(res.toString())
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="listvalue" name="selectedCB">
<input type="checkbox" name="checkedAll" id="checkedAll" />
<div class="tycheck">
  <input type="checkbox" name="checkAll" value="2" class="checkSingle" />
  <input type="checkbox" name="checkAll" value="1" class="checkSingle" />
  <input type="checkbox" name="checkAll" value="3" class="checkSingle" />
</div>

2 Comments

Hi, @prasanth Thank you for the help, but it didn't work when activating buttons: ['colvis'] in DataTable, I searched for solutions on the Internet, but it didn't seem to work.
@ChimDiTru for in you question there is no data tables are present

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.