0

below is the html code i would like to get the values of checkboxes seperated with comma in the textbox of id='selchk' and get the count of checkbox clicked in textbox of id='getcnt' and on uncheck the value should be removed and count should be reduced using jquery.i have tried but didn't achieve the result.need help

<input type='checkbox' class='chk' value='1'>        
<input type='checkbox' class='chk' value='2'>       
<input type='checkbox' class='chk' value='3'>        
<input type='checkbox' class='chk' value='4'>        
<input type='checkbox' class='chk' value='5'>        
<input type='checkbox' class='chk' value='6'>           
<input type='text' class='getcnt' id='getcnt'>        
<input type='text' class='selchk' id='selchk'>

2 Answers2

1

JsFiddle

var total = 0;

$(".chk").click(function(){

  var output = $.map($('.chk:checked'), function(n, i){
    return n.value;
  }).join(',');

  total = $('.chk:checked').length;
  $("#getcnt").val(total);
  $("#selchk").val(output);
});

JsFiddle

Community
  • 1
  • 1
Parthi04
  • 1,121
  • 4
  • 21
  • 39
1

CodePen Example

var $boxes = $('input[type=checkbox]'),
    $count = $('#getcnt'),
    $values = $('#selchk');

$boxes.click(function() {
    var values = [];
    var checked =0;
    $boxes.each(function() {
      if (this.checked) {
        values.push(this.value);
        checked++;
      }
    });
    $count.attr('value',checked);
    $values.attr('value',values.toString());
});
anthumchris
  • 8,245
  • 2
  • 28
  • 53