Files
AVSDevR.A11yShinyInputs/inst/js/a11yCheckboxGroupInput.js

89 lines
2.7 KiB
JavaScript

var a11yCheckboxGroupBinding = new Shiny.InputBinding();
$.extend(a11yCheckboxGroupBinding, {
find: function(scope) {
return $(scope).find(".shiny-input-a11ycheckboxgroup");
},
getValue: function(el) {
// Select the checkbox objects that have name equal to the grouping div's id
const $objs = $('input:checkbox[name="' + el.id + '"]:checked');
const values = new Array($objs.length);
for (let i = 0; i < $objs.length; i++) {
values[i] = $objs[i].value;
}
return values;
},
setValue: function(el, value) {
// Null value should be treated as empty array
value = value || [];
// Clear all checkboxes
$('input:checkbox[name="' + el.id + '"]').prop("checked", false);
// Accept array
if (value instanceof Array) {
for (let i = 0; i < value.length; i++) {
$('input:checkbox[name="' + el.id + '"][value="' + value[i] + '"]')
.prop("checked", true);
}
// Else assume it's a single value
} else {
$('input:checkbox[name="' + el.id + '"][value="' + value + '"]')
.prop("checked", true);
}
},
getState: function(el) {
const $objs = $('input:checkbox[name="' + el.id + '"]');
// Store options in an array of objects, each with with value and label
const options = new Array($objs.length);
for (let i = 0; i < options.length; i++) {
options[i] = {
value: $objs[i].value,
label: getLabel($objs[i])
};
}
return {
label: getLabelNode(el).text(),
value: this.getValue(el),
options: options,
};
},
receiveMessage: async function(el, data) {
const $el = $(el);
// This will replace all the options
if (Object.prototype.hasOwnProperty.call(data, "options") && data["options"] !== undefined) {
// Clear existing options and add each new one
$el.find("div.shiny-options-group").remove();
// Backward compatibility: for HTML generated by shinybootstrap2 package
$el.find("label.checkbox").remove();
$el.append(data.options);
$el.find('.select-all-container').appendTo($el)
}
if (Object.prototype.hasOwnProperty.call(data, "value") && data["value"] !== undefined) {
this.setValue(el, data.value);
}
if (Object.prototype.hasOwnProperty.call(data, "label") && data["label"] !== undefined) {
await updateLabel(data.label, $el.find("legend"));
}
$(el).trigger("change");
},
subscribe: function(el, callback) {
$(el).on("change.checkboxGroupInputBinding", function () {
callback(false);
});
},
unsubscribe: function(el) {
$(el).off(".checkboxGroupInputBinding");
}
});
Shiny.inputBindings.register(a11yCheckboxGroupBinding);