locked
jQuery default score if checkboxes are unchecked RRS feed

  • Question

  • User444756084 posted

    I have an MVC form that calculates a real time score based on 5 check boxes and radio buttons. Each radio button that is selected has an assign value that is added up then divided by 10 to give a percentage. However, if ALL check boxes are NOT checked the score needs to default to a score of 50. I can not get this to work. No errors the score just stays as 50.

     $(document).ready(function () {
            
             //score is set to 0% when form loads
             $('#score').val('0');         
    
             var form = $('#createform'),
                 //add other elements if needed
                 elements = form.find('[type="radio"]');
                
    
             //function to calculate total
             var calculateScore = function () {
                 var total = 0, cnt = 0;
    
                 $.each(elements, function () {
                     var field = $(this),
                         newVal;
    
                     // switch type
                     switch (field.prop('type')) {
                        
                         //case 'checkbox':
                         //    if ($(this).prop('checked') == false) {
                         //        //do something
                         //        newVal = 50;
                         //
                         //    } else {
                         //       // newVal = this.checked ? field.val() : 0;
                         //        newVal = 0;
                         //    }
                         //   break;
                         case 'radio':
                             newVal = this.checked ? field.val() : 0;
                             if (this.checked) { cnt += 1; }
                             break;
    
                     }
                      
                 
                    newVal = parseFloat(newVal);               
                    total += newVal;
                   
    
                    if ($('input[type=checkbox]:checkbox:not(:checked)').length == 0) {
                        // all are checked
                        $('#score').val(total / 10);
                        
                    } else if ($('input[type=checkbox]:checkbox:checked').length == 0) {
                        // all are unchecked
                        $('#score').val(50);
                    }
                  
                    
                 });
    
    
             };
    
             // bind events on change
             elements.on('change keyup', calculateScore);
    
    
    
    });

    Wednesday, April 4, 2018 6:49 PM

Answers

  • User2103319870 posted

    //add other elements if needed
                 elements = form.find('[type="radio"]');
     // bind events on change
             elements.on('change keyup', calculateScore);

    You are calling Calculate Score method only to radiobuttons. if you want to call the calculate score method on checkbox change then you need to attach function call to checkbox as well

    chkelements = form.find('[type="checkbox"]');
    
    .
    .
    .
    .
    
     // bind events on change
                chkelements.on('change keyup', calculateScore);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 4, 2018 7:31 PM

All replies

  • User475983607 posted

    There are quite a few logical errors.  I suggest that you learn how to set a breakpoint and step through the JavaScript.

    https://www.w3schools.com/js/js_debugging.asp

    Radio button are mutually exclusive.  Radio button are generally found in a group where only one radio can be selected.  

    Below is an example of using jQuery to get all the checkboxes and all the checked checkboxes.   

    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        
    </head>
    <body>
        <div>
            <input id="Checkbox1" name="Checkbox1" type="checkbox" checked />
            <input id="Checkbox2" name="Checkbox2" type="checkbox" checked />
            <input id="Checkbox3" name="Checkbox3" type="checkbox" checked />
            <input id="Checkbox4" name="Checkbox4" type="checkbox" checked />
            <input id="Checkbox5" name="Checkbox5" type="checkbox" />
        </div>
        <div id="result">
    
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script>
            var numberOfCheckBoxes = $('input:checkbox').length;
            var numberOfCheckedCheckBoxes = $('input:checkbox:checked').length;
            if (numberOfCheckBoxes == numberOfCheckedCheckBoxes) {
                $('#result').text("Equal");
            } else {
                $('#result').text("Not Equal");
            }
    
            console.log(numberOfCheckBoxes);
            console.log(numberOfCheckedCheckBoxes);
        </script>
    </body>
    </html>

    Wednesday, April 4, 2018 7:26 PM
  • User2103319870 posted

    //add other elements if needed
                 elements = form.find('[type="radio"]');
     // bind events on change
             elements.on('change keyup', calculateScore);

    You are calling Calculate Score method only to radiobuttons. if you want to call the calculate score method on checkbox change then you need to attach function call to checkbox as well

    chkelements = form.find('[type="checkbox"]');
    
    .
    .
    .
    .
    
     // bind events on change
                chkelements.on('change keyup', calculateScore);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 4, 2018 7:31 PM
  • User444756084 posted

    I know that radio buttons are exclusive. I am not having an issue with that. My issue is getting the score to default if checkboxes are not all checked. Thanks for the debugging tip.

    Wednesday, April 4, 2018 7:58 PM
  • User475983607 posted

    gordon1221

    I know that radio buttons are exclusive. I am not having an issue with that. My issue is getting the score to default if checkboxes are not all checked. Thanks for the debugging tip.

    See my previous post which shows how to compare checked vs All.

    It can be done in one line too.

    var result = $('input:checkbox').length == $('input:checkbox:checked').length ? (10 / 10) * 100 : 50
    console.log(result)

    Also, we cannot see the source code.  For all we know the total variable could equal 500.  That's why I suggest you try stepping through the code to make sure it is working as expected. Maybe post the HTML as well.

    Wednesday, April 4, 2018 8:14 PM
  • User1400794712 posted

    Hi gordon1221,

    My issue is getting the score to default if checkboxes are not all checked.

    You can add click event for each checkbox to check if checkboxes are checked.

    <label id="score"></label>
    <script>
        var total=100
        function checkBox() {
            if ($('input[type=checkbox]:checkbox:not(:checked)').length == 0) {
                // all are checked
                $('#score').html(total / 10);
    
            } else if ($('input[type=checkbox]:checkbox:checked').length == 0) {
                // all are unchecked
                $('#score').html(50);
            } else {
                $('#score').html(20);
            }
        }
        $(document).ready(function () {           
            checkBox();
            $("body").on("click", "input[type='checkbox']", checkBox);
        })
    </script>

    How it works:

    Best Regards,

    Daisy

    Thursday, April 5, 2018 9:08 AM
  • User-474980206 posted

    the "spec" say each check box has a value, so the correct code is:

    $(function() {
      var defaultScore = "50";
      $('#score').val(defaultScore);
      $('#createform input[type=checkbox]')
        .click(function () {
           // get all checked boxes
           var list = $('#createform input[type=checkbox]:checked').toArray();
    
           // none checked then 50, else ((sum values) / 10) convert to string
           $('#score')
               .val(list.length == 0
                    ? defaultScore
                    : list.reduce(function(p,c){
                         return p + parseInt(c.value)
                      },0) / 10.0 + ''
               );
        });
    });
    

    Friday, April 6, 2018 6:03 PM