Limit Checkbox List Selection

jQuery( document ).ready( function(){
var myListController = Marionette.Object.extend({
initialize: function() {
// Listen to the value change for Checkbox List fields.
this.listenTo( Backbone.Radio.channel( 'listcheckbox' ), 'change:modelValue', this.onChangeModelValue );
},
onChangeModelValue: function( fieldModel ) {
// Use the field key to check for a specific field.
// The field key can be set/checked in the field's settings (under the Administration section).
if( 'my_checkbox_list' !== fieldModel.get( 'key' ) ) return;
// Set the limit of options to select.
var limit = 9;
var value = fieldModel.get( 'value' );
_.each( fieldModel.get( 'options' ), function( option ){
// If the option is not selected and the limit has been reached…
if( ! value.includes( option.value ) && Array.isArray( value ) && limit <= value.length ){
// Disable the unselected option.
jQuery( '#nf-field-' + fieldModel.get( 'id' ) + '-' + option.index ).attr( 'disabled', 'disabled' );
} else {
// Enable the option, selected or not.
jQuery( '#nf-field-' + fieldModel.get( 'id' ) + '-' + option.index ).attr( 'disabled', false );
}
});
}
});
new myListController();
});