0

I've multiple checkboxes which are populated from database, except one checkbox which is "All" (used to check/uncheck all other checkboxes onclick)

  1. When all the options are checked and if any option other than 'All' is unchecked then checkbox of All should be unchecked.

  2. When all the option are checked except 'All' then 'All' should be checked. How to proceed?

My code:

<script>
    $(document).ready(function () {
        ('#check').append('<input type="checkbox"  id="checkAll" name="myCheckbox[]" value="All" > </input>' + "All" );
        //'datadb' is data from db in json array 
        //datadb={'apple','banana','orange'}

        $.each(datadb, function(i, fruit) {
            $('#check').append('<input type="checkbox" name="myCheckbox[]" class=".chk"  value="' + fruit + '" > </input>' + fruit );
            $('#check').append('<br/>');        
        }
    });
</script>

<script>            
    $(document).ready(function() {
        $("#checkAll").click(function () {
            $('input:checkbox').not(this).removeProp('checked');
        });
    });
</script>
<div id="check" onchange="testingclick()"></div>

How to fill the function to satisfy above 1 and 2

<script>
    function testingclick(){
        var $check_values = $("input[type=checkbox][name='myCheckbox[]']:checked");
        var $check_len = $check_values.length;
        var $total_len = $("input[type=checkbox][name='myCheckbox[]']").length;

        window.var_multiple_checked = $check_values.map(function(){  return "'" + this.value + "'";   }).get(); 
        temp_checked= window.var_multiple_checked;
    }
</script>
2
  • is this what you're trying to do? Commented Nov 11, 2014 at 11:55
  • Yes, exactly, spent quite a good time for it. Thank you @billyonecan . Commented Nov 11, 2014 at 11:59

1 Answer 1

0

For this code.

$('input:checkbox').not(this).prop('checked', this.checked);

Try to use removeProp instead

$('input:checkbox').not(this).removeProp('checked');

And for the events of your checkbox. Hook all with event.

$(document).ready(function() {
    $('input:checkbox').click(function () {
        if ($(this).attr('id') === 'checkAll' && $(this).is(':checked')) {
            $('input:checkbox').not($(this)).removeProp('checked');
        } else {
            $('#checkAll').removeProp('checked');
        }
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Edited it. Any suggestion to fulfill the funciton?

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.