user2463248
user2463248

Reputation: 167

Javascript - check/uncheck checkbox after summing different inputs

I have a ‘parent’ <div>, and ‘child’ divs which are shown after clicking parent <div>. All divs have <checkboxes> and <input> to put quantity.

Parent <checkbox> checks when at least one child <checkbox> is checked.

When child <checkbox> is checked/unchecked the quantity in <input> is automatically changed into ‘1’ or ‘’.

Parent quantity <input> is disabled and it is supposed to show the sum of all children quantities.

I have two problems.

First, the summing script works fine when you enter the quantity yourself, however when the quantity appears/disappears itself (after checking/unchecking the child <checkbox>) the summing script does not react on such change.

Secondly I wasn’t able to uncheck the parent <checkbox> when all child checkboxes are unchecked. However I’m assuming if the summing script will start working properly I will be able to bind the parent <checkbox> with the sum (if (sum> 0){ $('#checkbox0').prop('checked', true);}else{$('#checkbox0').prop('checked', false);}

Html:

    <div class="divCell" id="click1">
    <div class="checkbox_div" style='pointer-events:none;'>
      <input type="checkbox" id="checkbox0">
    </div>   
    <div class="div_name_divcell">Parent - click to open</div>
    <div class="div_quantity_divcell">
    <input type="text" name="parent_1" class="quantity_class_parent_1" id="quantity_parent_1" size="1" maxlength="3" onkeypress="return numbersonly(this, event)" disabled="disabled">
   </div>
</div>
<div id="hidden1" style="display: none;">
 <div class="divCell" id="child_click1">
    <div class="checkbox_div">
      <input type="checkbox" id="checkbox1">
    </div>   
    <div class="div_name_divcell">Child1</div>
    <div class="div_quantity_divcell">
      <input type="text" name="child_1" class="quantity_class_child" id="quantity_child_1" size="1" maxlength="3" onkeypress="return numbersonly(this, event)">
   </div>
 </div>

  <div class="divCell" id="child_click2">
    <div class="checkbox_div">
      <input type="checkbox" id="checkbox2">
    </div>   
    <div class="div_name_divcell">Child2</div>
    <div class="div_quantity_divcell">
      <input type="text" name="child_1" class="quantity_class_child" id="quantity_child_2" size="1" maxlength="3" onkeypress="return numbersonly(this, event)">
   </div>
 </div>
</div>

Css:

.divCell {width: 500px;height: 35px;margin: 2px 0;display: inline-block;background-color: #D4F78F;}
.div_quantity_divcell{float:right; padding:9px 1px 0 0}
.checkbox_div {width: 25px;position: relative;margin: 5px;float: left;}
.div_name_divcell {line-height: 35px;width: auto;float: left;}

JavaScript:

    $(document).ready( function() {
        event.preventDefault();
        $('#checkbox1').click(function() {
        if(this.checked){     
            $('#checkbox0').prop('checked', this.checked); 
            $('#quantity_child_1').val('1')     
        }else{ 
            $('#quantity_child_1').val('')
        //$('#checkbox0').prop('checked', false);
        }});
        $('#quantity_child_1').keyup(function(){
            $('#checkbox1').prop('checked', this.value > 0);
        $('#checkbox0').prop('checked', true);
        })
      //second child
        $('#checkbox2').click(function() {
        if(this.checked){     
            $('#checkbox0').prop('checked', this.checked); 
            $('#quantity_child_2').val('1')     
        }else{ 
            $('#quantity_child_2').val('') 
        //$('#checkbox0').prop('checked', false);
        }});
        $('#quantity_child_2').keyup(function(){
            $('#checkbox2').prop('checked', this.value > 0);
        $('#checkbox0').prop('checked', true);
        })
    });
    // suming script

    $(document).on('change', '.quantity_class_child', function(){
        var sum = 0;
        $('.quantity_class_child').each(function(){
        sum += +$(this).val();
        });

        $('#quantity_parent_1').val(sum);
    });

//opening script
$(document).ready(function() {
  $('#click1').click(function() {
        if ($('#hidden1').is(':hidden')) {
       $('#hidden1').show(500);
    } else {
       $('#hidden1').hide(500);
    }
  });
});

JSFiddle: https://jsfiddle.net/mamzj4tw/6/

Upvotes: 2

Views: 1036

Answers (4)

Kokovin Vladislav
Kokovin Vladislav

Reputation: 10391

You can add new elements https://jsfiddle.net/mamzj4tw/34/

$(document).ready( function() {
    $('.drop-down #checkbox').on('change',function(){
        $(this).closest('.divCell').find('#quantity_child')
        .val(this.checked ? 1:'').trigger('keyup');
    });

    $(document).on('keyup click', '.quantity_class_child', function(){
        $(this).closest('.divCell').find('#checkbox').prop("checked",+$(this).val());
        var sum = 0;
        $('.quantity_class_child').each(function(){sum += +$(this).val()});
        $('#quantity_parent_1').val(sum ||'');
        $('#checkbox0').prop("checked", sum);
    });

    $('#click1').click(function() { $('#hidden1').toggle(500); });
});

Upvotes: 0

Ralf
Ralf

Reputation: 1

Your code was a bit to complicated, so i have rewritten what you tried to archive ( without the css part). fiddle here

three little html div's

<div class="parent" id="parent">
 <span class="input">
  <input type="checkbox" name="parent" value="">
  <label for parent>parent - click to open</label>
  <input type="text" name="sum">
 </span> 
</div>
<div class="child" id="child1">
 <span class="input">
  <input type="checkbox" class="inputCheckbox" name="child1" value="child1">
  <input type="text" class="inputSum" name="sum1">
 </span> 
</div>
<div class="child" id="child2">
 <span class="input">
  <input type="checkbox" class="inputCheckbox" name="child2" value="child2">
  <input type="text" class="inputSum" name="sum2">
 </span> 
</div>

and a bit of jquery

$('.child').hide(); 
// check if parent checkbox is checked

$('input[name="parent"]').click ( function () { 
  if ( $(this).is(':checked') ) $('.child').show(); else $('.child').hide();
})

// check if childcheckbox is checked , if true trigger keyup and sum
$('.inputCheckbox').on ( 'change', function () {  
 if ( $(this).is(':checked') )  $(this).next().val('1').keyup();
// if not , trigger parent
 if ( ! $('.inputCheckbox').is(':checked')  ) $('input[name="parent"]').click ();  
})
// check if value is entered and sum it on keyup
$('.inputSum').on('keyup', function () {  
 var sum = 0;
 $('.inputSum').each ( function () { sum +=  ( $(this).val() - 0)   })
 $('input[name="sum"]').val(sum)
})

HTH

Upvotes: 0

Runcorn
Runcorn

Reputation: 5224

Ok, Here are the things that you can do to achieve,

First, the summing script works fine when you enter the quantity yourself, however when the quantity appears/disappears itself (after checking/unchecking the child ) the summing script does not react on such change.

The thing is change event will not be triggered if you are setting/changing the value from the javascript. For this you can manually call the change event to trigger the effect. Or, Create a separate function for summation calculation and call it on uncheck event of the checkbox.

eg.

Either

$('#checkbox1').click(function() {
    if (this.checked) {
      $('#checkbox0').prop('checked', this.checked);
      $('#quantity_child_1').val('1')
    } else {
      $('#quantity_child_1').val('')
      $(".quantity_class_child").trigger("change");
        //$('#checkbox0').prop('checked', false);
    }
  });

OR

$('#checkbox1').click(function() {
    if (this.checked) {
      $('#checkbox0').prop('checked', this.checked);
      $('#quantity_child_1').val('1')
    } else {
      $('#quantity_child_1').val('');
        summation();
    }
  });

function summation(){
  var sum = 0;
  $('.quantity_class_child').each(function() {
    sum += +$(this).val();
  });
  $('#quantity_parent_1').val(sum);
 }

Now for the second part,

Secondly I wasn’t able to uncheck the parent when all child checkboxes are unchecked.

Just check the length of the checked input box during the summation process and uncheck it if the the length is zero.

Hope this help you cause.

Upvotes: 1

Diego Betto
Diego Betto

Reputation: 730

This is an updated version of your version

https://jsfiddle.net/mamzj4tw/13/

It uses each() to better (and clean) add actions to inputs.

You can create your custom events like do-sum and fire when you want. In this case I defined that the sum is executed when $(document).trigger('do-sum');
fires do-sum event.

and I've set a listener that executes your routine:

$(document).on('do-sum', function(){ var sum = 0; $('.quantity_class_child.active').each(function(){ sum += +$(this).val(); }); $('#quantity_parent_1').val(sum); var parentChecked = false; $('#hidden1 input[type="checkbox"]').each(function(i, e){ if($(e).is(':checked')) { parentChecked = true; } }); $('#checkbox0').prop('checked', parentChecked); });

I also use class active to set valid inputs (and quick sum them).

PS you don't need event.preventDefault(); after document ready event.

Upvotes: 2

Related Questions