jQuery checkbox check-uncheck

jQuery .prop() gets or sets the value of a property for the target element;

js:

$(function(){
    $('.check-all').click(function() {
        $('.checkbox input').prop('checked', true); // check all checkboxes
        $('.radio input').prop('checked', true); // check first radio
    });
    $('.uncheck-all').click(function() {
        $('.checkbox input').prop('checked', false); // uncheck all checkboxes
        $('.radio input').prop('checked', false); // uncheck first radio
    });
    $('.test-checkbox').click(function() {
        if ($('.checkbox:first input').is(':checked')) {
            $('.test-log').text('checked');
        } else {
            $('.test-log').text('unchecked');
        }
    });
});

html:

<form class="well">
    <p class="help-block">
        <button class="btn check-all">check all checkboxes and radio</button>
        <button class="btn uncheck-all">uncheck all checkboxes and radio</button>
        <button class="btn test-checkbox">test first checkbox</button>
    </p>
    <label class="checkbox">
        <input type="checkbox"> checkbox 1 
        <strong class="label test-log"></strong>
    </label>
    <label class="checkbox">
      <input type="checkbox"> checkbox 2
    </label>
    <label class="radio">
      <input type="radio" name="radio"> radio 1
    </label>
    <label class="radio">
      <input type="radio" name="radio"> radio 2
    </label>
</form>‚Äč

Leave a Reply

Your email address will not be published. Required fields are marked *