Checkbox Select Deselect All And Perform Function
I have a bunch of checkboxes that when clicked pass their value to a text area. I then have a checkbox that when clicked selects all the other checkboxes. This is all working fine.
Solution 1:
If you're already using jQuery, you could do it without loops, with jQuery's .on()/.trigger()/.change():
var $result = $('.js-result');
var $checkboxes = $('.js-checkbox');
$checkboxes.on('change', function(e) {
var $checkbox = $(e.target);
$result.append(
'<div>' +
$checkbox.closest('.js-label').text() + ' is ' +
($checkbox.prop('checked') ? 'checked' : 'unchecked') +
'</div>'
);
});
$('.js-button').on('click', function() {
var $this = $(this);
$checkboxes.prop('checked', !$this.data('checked'));
$checkboxes.trigger('change');
$this.data('checked', !$this.data('checked'))
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><labelclass="js-label"><inputtype="checkbox"class="js-checkbox"/>
Checkbox 1
</label><labelclass="js-label"><inputtype="checkbox"class="js-checkbox"/>
Checkbox 2
</label><labelclass="js-label"><inputtype="checkbox"class="js-checkbox"/>
Checkbox 3
</label><buttontype="button"class="js-button">Check/uncheck all</button><divclass="js-result"></div>
Post a Comment for "Checkbox Select Deselect All And Perform Function"