Published
Edited
Feb 20, 2018
1 fork
Importers
3 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function multiChoice(config = {}) {
const {title, description, placeholder, submit, options} = config;
const checked = config.value
const isChecked = value => type === 'checkbox' ? (checked || []).indexOf(value) > -1 : value === checked

const type = config.type === 'radio' || config.type === 'checkbox' ? config.type : 'radio'
const _options = (Array.isArray(config) ? config : options)
.map(o => typeof o === 'string' ? { value: o, label: o } : o)

const getValue = input => {
if (type === 'checkbox') {
return Array.prototype.filter.call(input, radio => radio.checked).map(input => input.value)
}
const checked = Array.prototype.find.call(input, radio => radio.checked)
return checked ? checked.value : undefined
}
const form = input({
title, description, submit,
form: html`
<form>
${ _options.map(({value, label}) => `
<label><input
type=${type}
name=input
value=${value}
${isChecked(value) ? 'checked' : ''}
>${label}&nbsp;</label>
`)}
</form>
`,
// By making some simple changes to @jashkenas/input (support for subscribing to the form's
// `onchange` event), this code could be spared from declaring `action()`
action: form => {
const update = (e) => {
e && e.preventDefault();
form.value = getValue(form.input)
form.dispatchEvent(new CustomEvent("input"))
}
form.onchange = update
update()
}
})
form.output.remove();
form.style.fontSize = "1em";
return form;
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more