Chim Di Tru
Chim Di Tru

Reputation: 523

How to get a Checkbox Value in JavaScript

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. :(

Upvotes: 1

Views: 7985

Answers (2)

prasanth
prasanth

Reputation: 22490

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>

Upvotes: 0

T&#226;n
T&#226;n

Reputation: 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>

Upvotes: 1

Related Questions