### Configured Textarea Input with Label and Placeholder (JavaScript) Source: https://observablehq.com/framework/inputs/textarea Demonstrates how to configure a textarea input with a descriptive label and a placeholder to guide user input. An initial value can also be provided. ```javascript const bio = view(Inputs.textarea({label: "Biography", placeholder: "What’s your story?"})); ``` -------------------------------- ### Create Sorted and Unique Select Input Source: https://observablehq.com/framework/inputs/select This example demonstrates creating a select input with options that are both sorted alphabetically and de-duplicated. The `sort: true` and `unique: true` options ensure a clean and organized list of sports derived from the Olympian dataset. ```javascript const sport = view( Inputs.select( olympians.map((d) => d.sport), {label: "Sport", sort: true, unique: true} ) ); ``` -------------------------------- ### Create Select with Map for Options and Default Value Source: https://observablehq.com/framework/inputs/select This example shows how to create a select dropdown using a JavaScript Map for the options. The keys of the Map are displayed as options, and the values are the actual selected values. A default value is set using the 'value' option, and the selection is stored in 'size'. ```javascript const size = view( Inputs.select( new Map([ ["Short", 8], ["Tall", 12], ["Grande", 16], ["Venti", 20] ]), {value: 12, label: "Size"} ) ); ``` -------------------------------- ### Button with HTML Content Source: https://observablehq.com/framework/inputs/button Renders a button with custom HTML content using the `html` tag. In this example, the button displays the emphasized text 'Fancy'. ```javascript const y = view(Inputs.button(html`Fancy`)); ``` -------------------------------- ### Range Input with Initial Value Source: https://observablehq.com/framework/inputs/range Initializes a range input with a specific starting value. The initial value defaults to the midpoint of the min and max range if not provided. ```javascript const z = view(Inputs.range([0, 255], {step: 1, value: 0})); ``` -------------------------------- ### Preselect Rows in an Observable Table Source: https://observablehq.com/framework/inputs/table This example demonstrates how to preselect specific rows in an Observable Framework table by providing an array of data objects to the `value` option. It shows how to select the first two rows or a custom selection of rows using array slicing. ```javascript penguins.slice(0, 2) ``` -------------------------------- ### Radio Input with Map and Custom Formatting Source: https://observablehq.com/framework/inputs/radio Extends the Map example by providing a custom `format` function to display both the key (name) and value (ounces) from the Map entries. ```javascript const size2 = view( Inputs.radio( new Map([ ["Short", 8], ["Tall", 12], ["Grande", 16], ["Venti", 20] ]), {value: 12, label: "Size", format: ([name, value]) => `${name} (${value} oz)`} ) ); ``` -------------------------------- ### Create Single-Select Dropdown with Optional Null Value Source: https://observablehq.com/framework/inputs/select This example demonstrates creating a single-select dropdown where the first option is 'null', allowing the user to select no option. It uses the Inputs.select function with a predefined list of colors. The selected value is stored in 'maybeColor'. ```javascript const maybeColor = view(Inputs.select([null].concat(x11colors), {label: "Favorite color"})); ``` -------------------------------- ### Create Multi-Select Input with Array Value Source: https://observablehq.com/framework/inputs/select This code example shows how to create a select input that allows multiple selections. The 'multiple: true' option enables this functionality, and the input's value will be an array of the selected items. The initial value is an empty array. ```javascript const colors = view(Inputs.select(x11colors, {multiple: true, label: "Favorite colors"})); ``` -------------------------------- ### Initialize Search Input with Placeholder Source: https://observablehq.com/framework/inputs/search This snippet demonstrates how to initialize a search input component using the `Inputs.search` function from Observable Framework. It takes the dataset and an options object, including a placeholder string for the input field. The result is a view that can be integrated into an Observable notebook. ```javascript const search = view(Inputs.search(penguins, {placeholder: "Search penguins…"})); ``` -------------------------------- ### Import Observable Inputs Library (JavaScript) Source: https://observablehq.com/framework/inputs/index Imports the entire Observable Inputs library for use in JavaScript projects. This allows access to all available input components. ```javascript import * as Inputs from "npm:@observablehq/inputs"; ``` -------------------------------- ### Create Basic Text Input Source: https://observablehq.com/framework/inputs/text Demonstrates the simplest way to create a text input. The value of this input will be an empty string initially and will update as the user types. ```javascript const text = view(Inputs.text()); ``` -------------------------------- ### Initializing a table with pre-selected rows using Inputs.table Source: https://observablehq.com/framework/inputs/table This JavaScript code snippet shows how to use the `Inputs.table` function to display tabular data. The `value` option is used to specify an initial set of pre-selected rows, which are determined by mapping indices to the `penguins` data. The `multiple` option is set to `true`, allowing multiple rows to be selected. ```javascript Inputs.table(penguins, { value: [1, 3, 7, 9].map((i) => penguins[i]), multiple: true }) ``` -------------------------------- ### Configure Text Input with Label, Placeholder, and Value Source: https://observablehq.com/framework/inputs/text Shows how to enhance a text input's usability by providing a label, a placeholder, and an initial default value. This makes the input's purpose clearer to the user. ```javascript const name = view( Inputs.text({ label: "Name", placeholder: "Enter your name", value: "Anonymous" }) ); ``` -------------------------------- ### Create Text Input with Datalist Suggestions Source: https://observablehq.com/framework/inputs/text Demonstrates how to provide a list of suggested values for a text input using the `datalist` option. This improves user experience by offering autocomplete functionality. ```javascript const capitals = FileAttachment("us-state-capitals.tsv").tsv({typed: true}); const state = view(Inputs.text({ label: "U.S. state", placeholder: "Enter state name", datalist: capitals.map((d) => d.State) })); ``` -------------------------------- ### Configure Table Layout, Width, and Alignment Source: https://observablehq.com/framework/inputs/table This snippet shows how to configure the appearance and behavior of an Inputs.table. It specifies fixed widths and alignment for individual columns, sets the number of rows to display, defines a maximum table width, and enforces a 'fixed' layout for consistent column packing. ```javascript Inputs.table(penguins, { width: { culmen_length_mm: 140, culmen_depth_mm: 140, flipper_length_mm: 140 }, align: { culmen_length_mm: "right", culmen_depth_mm: "center", flipper_length_mm: "left" }, rows: 18, maxWidth: 840, multiple: false, layout: "fixed" }) ``` -------------------------------- ### Button with Label and Text Content Source: https://observablehq.com/framework/inputs/button Creates a button labeled 'Continue?' with the text 'OK'. This demonstrates how to apply a label to a button alongside its primary content. ```javascript const confirm = view(Inputs.button("OK", {label: "Continue?"})); ``` -------------------------------- ### Create a basic date input Source: https://observablehq.com/framework/inputs/date Demonstrates the creation of a simple date input using the `Inputs.date()` function. The value of this input is a Date instance at UTC midnight, or null if no initial value is specified. ```javascript const date = view(Inputs.date()); ``` -------------------------------- ### Image File Input Source: https://observablehq.com/framework/inputs/file Creates a file input for image files. It accepts .png or .jpg files and provides a method to display the selected image. ```javascript const imgfile = view(Inputs.file({label: "Image file", accept: ".png,.jpg", required: true})); // Display the selected image imgfile.image() ``` -------------------------------- ### Import Specific Observable Inputs (JavaScript) Source: https://observablehq.com/framework/inputs/index Imports only specific input components, such as 'button' and 'color', from the Observable Inputs library. This is useful for reducing bundle size by only including necessary components. ```javascript import {button, color} from "npm:@observablehq/inputs"; ``` -------------------------------- ### Create a date input with label and initial value Source: https://observablehq.com/framework/inputs/date Shows how to initialize a date input with a user-friendly label and a predefined value. The initial value can be a Date instance, a 'YYYY-MM-DD' string, or milliseconds since UNIX epoch. Providing a label is recommended for better usability. ```javascript const start = view(Inputs.date({label: "Start", value: "2021-09-21"})); ``` -------------------------------- ### Checkbox Input: HTML Formatting and Initial Value Source: https://observablehq.com/framework/inputs/checkbox Illustrates advanced customization using an HTML element for the 'label' and a 'format' function that returns HTML for each option. The 'value' option sets the initially selected item(s). ```javascript const colors2 = view( Inputs.checkbox(["red", "green", "blue"], { value: ["red"], label: html`Colors`, format: (x) => html`${x}` }) ); ``` -------------------------------- ### Color Input with D3 for Flexibility Source: https://observablehq.com/framework/inputs/color Demonstrates using D3.js to parse and format CSS colors into hexadecimal strings for the color input. This provides greater flexibility than the default strict hexadecimal input. Requires the D3 library. ```javascript const fill = view(Inputs.color({label: "Fill", value: d3.color("steelblue").formatHex()})); ``` -------------------------------- ### Create a date input with min and max bounds Source: https://observablehq.com/framework/inputs/date Shows how to set acceptable date ranges for an input using the `min` and `max` options. These bounds can be specified as Date instances, 'YYYY-MM-DD' strings, or epoch milliseconds. ```javascript const birthday = view(Inputs.date({label: "Birthday", min: "2021-01-01", max: "2021-12-31"})); ``` -------------------------------- ### Color Input with Datalist Source: https://observablehq.com/framework/inputs/color Configures a color input with a predefined list of colors using the `datalist` option. This provides users with convenient color choices. The input still allows users to pick colors outside the datalist. ```javascript const stroke = view(Inputs.color({label: "Stroke", datalist: d3.schemeTableau10})); ``` -------------------------------- ### Create a Search Input with Table Filtering (JavaScript) Source: https://observablehq.com/framework/inputs/index Creates a search input component that filters rows from a provided dataset, such as a table. The search input's value is the subset of rows that match the query. It supports prefix matching against all columns and can include a datalist for suggestions. ```javascript const searchResults = view(Inputs.search(olympians, { datalist: ["mal", "1986", "USA gym"], placeholder: "Search athletes" })) ``` -------------------------------- ### Create Password Input Source: https://observablehq.com/framework/inputs/text Demonstrates how to create a password input field using the `Inputs.password` convenience method. This masks the user's input for security purposes. ```javascript const password = view(Inputs.password({label: "Password", value: "open sesame"})); ``` -------------------------------- ### Create a Basic Button Input Source: https://observablehq.com/framework/inputs/button Creates a simple button input that emits an _input_ event when clicked. This can be used to trigger cell evaluations or other actions. The button's label is set to 'Replay'. ```javascript const replay = view(Inputs.button("Replay")); replay; // run this block when the button is clicked ``` -------------------------------- ### Text File Input Source: https://observablehq.com/framework/inputs/file Creates a file input for text files. It requires the user to select a .txt file and provides a method to read the selected file's content as text. ```javascript const textfile = view(Inputs.file({label: "Text file", accept: ".txt", required: true})); // Read the selected text file textfile.text() ``` -------------------------------- ### Basic File Input Source: https://observablehq.com/framework/inputs/file Creates a file input element. By default, any file is allowed, and the exposed value resolves to null until a file is selected. ```javascript const file = view(Inputs.file()); // Display the selected file (initially null) file ``` -------------------------------- ### ZIP Archive Input Source: https://observablehq.com/framework/inputs/file Creates a file input for ZIP archives. It requires the user to select a .zip file and provides a method to process the selected ZIP archive. ```javascript const zipfile = view(Inputs.file({label: "ZIP archive", accept: ".zip", required: true})); // Process the selected ZIP archive zipfile.zip() ``` -------------------------------- ### Create Compound RGB Input with Array of Ranges Source: https://observablehq.com/framework/inputs/form Demonstrates creating a compound form input for RGB channels using an array of range inputs. This is useful for a compact display of closely related numerical inputs. ```javascript const rgb = view(Inputs.form([ Inputs.range([0, 255], {step: 1, label: "r"}), Inputs.range([0, 255], {step: 1, label: "g"}), Inputs.range([0, 255], {step: 1, label: "b"}) ])); ``` -------------------------------- ### Create Toggle Input with Default Value (JavaScript) Source: https://observablehq.com/framework/inputs/toggle Demonstrates how to create a basic toggle input using the Inputs.toggle function. The initial value defaults to false. This is useful for simple on/off switches. ```javascript const mute = view(Inputs.toggle({label: "Mute", value: true})); ``` -------------------------------- ### Checkbox Input: Map Data with Initial Value Source: https://observablehq.com/framework/inputs/checkbox Demonstrates using a Map for checkbox data, where keys are displayed options and values are the actual data. The 'value' option sets the initial selection based on Map values. ```javascript const sizes = view( Inputs.checkbox( new Map([ ["Short", 8], ["Tall", 12], ["Grande", 16], ["Venti", 20] ]), {value: [12], label: "Size"} ) ); ``` -------------------------------- ### Multiple File Input Source: https://observablehq.com/framework/inputs/file Creates a file input that allows the user to select multiple files. The exposed value in this mode is an array of selected files. ```javascript const files = view(Inputs.file({label: "Files", multiple: true})); // Display the array of selected files (initially empty) files ``` -------------------------------- ### Create a datetime input Source: https://observablehq.com/framework/inputs/date Demonstrates the creation of a datetime input, which allows specifying both date and time. The time is interpreted in the user's local time zone. The input's value is exposed as a Date instance, formatted as UTC by the Observable inspector. ```javascript const datetime = view(Inputs.datetime({label: "Moment"})); ``` -------------------------------- ### Create Toggle Input with HTML Label (JavaScript) Source: https://observablehq.com/framework/inputs/toggle Illustrates using an HTML element for the toggle input's label. This provides greater flexibility in styling the label, allowing for rich text or complex HTML structures. ```javascript const fancy = view(Inputs.toggle({label: html`Fancy`})); ``` -------------------------------- ### Create Compound RGB Input with Object of Ranges Source: https://observablehq.com/framework/inputs/form Illustrates creating a compound form input for RGB channels by passing an object of range inputs. The resulting form input will have an object structure corresponding to the keys provided. ```javascript const rgb2 = view(Inputs.form({ r: Inputs.range([0, 255], {step: 1, label: "r"}), g: Inputs.range([0, 255], {step: 1, label: "g"}), b: Inputs.range([0, 255], {step: 1, label: "b"}) })); ``` -------------------------------- ### Display a Table Input (JavaScript) Source: https://observablehq.com/framework/inputs/index Renders a table input component using Observable Inputs. This component is suitable for displaying tabular data, allowing users to interact with rows via checkboxes. The selected rows form the input's value. ```javascript Inputs.table(olympians) ``` -------------------------------- ### Display Data in a Table Filtered by Search Source: https://observablehq.com/framework/inputs/search This code shows how to use the initialized search input to filter a table. The `Inputs.table` function takes the search view as an argument, automatically displaying the data that matches the current search query. This is a common pattern for interactive data exploration. ```javascript Inputs.table(search) ``` -------------------------------- ### Radio Input with Map Values Source: https://observablehq.com/framework/inputs/radio Shows how to use a Map as data for a radio input. The Map's keys are displayed as options, and its values are the associated data. The `value` option sets the initial selection. ```javascript const size = view( Inputs.radio( new Map([ ["Short", 8], ["Tall", 12], ["Grande", 16], ["Venti", 20] ]), {value: 12, label: "Size"} ) ); ``` -------------------------------- ### Basic Color Input Usage Source: https://observablehq.com/framework/inputs/color Creates a color input with a label and an initial value. The input returns a hexadecimal string representing the selected RGB color. It defaults to black ('#000000') if no value is provided. ```javascript const color = view(Inputs.color({label: "Favorite color", value: "#4682b4"})); ``` -------------------------------- ### Button to Restart Animation Source: https://observablehq.com/framework/inputs/button Demonstrates using a button to restart an animation. The `replay` button triggers the execution of the `progress` generator, which handles the animation logic. Generators are useful here as they are automatically interrupted when invalidated. ```javascript const replay = view(Inputs.button("Replay")); replay; // run this block when the button is clicked const progress = (function* () { for (let i = canvas.width; i >= 0; --i) { context.clearRect(0, 0, canvas.width, context.height); context.fillRect(0, 0, i, context.height); yield canvas; } })(); ``` -------------------------------- ### JSON File Input Source: https://observablehq.com/framework/inputs/file Creates a file input for JSON files. It requires the user to select a .json file and provides a method to parse the selected file as JSON. ```javascript const jsonfile = view(Inputs.file({label: "JSON file", accept: ".json", required: true})); // Parse the selected JSON file jsonfile.json() ``` -------------------------------- ### Radio Input with HTML Formatting Source: https://observablehq.com/framework/inputs/radio Demonstrates using HTML elements for labels and formatting in a radio input. The `format` function can return HTML, allowing for custom styling of each option. ```javascript const color2 = view( Inputs.radio(["red", "green", "blue"], { value: "red", label: html`Colors`, format: (x) => html`${x}` }) ); ``` -------------------------------- ### Button to Copy to Clipboard Source: https://observablehq.com/framework/inputs/button Creates a button that, when clicked, attempts to copy the value of the `time` variable to the system clipboard using the `navigator.clipboard.writeText()` API. The button itself does not display a value initially. ```javascript Inputs.button("Copy to clipboard", {value: null, reduce: () => navigator.clipboard.writeText(time)}) ``` -------------------------------- ### Create a Sparkbar Visualization Function Source: https://observablehq.com/framework/inputs/table This JavaScript function, `sparkbar`, generates HTML elements to create a visual bar within a table cell. It calculates the width of the bar based on the cell's value relative to a provided maximum value, suitable for visualizing progress or magnitude. ```javascript function sparkbar(max) { return (x) => htl.html`
${x.toLocaleString("en-US")}` } ``` -------------------------------- ### Excel File Input Source: https://observablehq.com/framework/inputs/file Creates a file input for Excel (.xlsx) files. It requires the user to select an .xlsx file and provides a method to parse the selected file as an Excel spreadsheet. ```javascript const xlsxfile = view(Inputs.file({label: "Excel file", accept: ".xlsx", required: true})); // Parse the selected Excel file xlsxfile.xlsx() ``` -------------------------------- ### Basic Radio Input with String Array Source: https://observablehq.com/framework/inputs/radio Creates a radio input for selecting a color from a list of strings. The `Inputs.radio` function takes an array of possible values and an options object for customization. ```javascript const color = view(Inputs.radio(["red", "green", "blue"], {label: "color"})); ``` -------------------------------- ### Format Table Columns with Sparkbars and Customization Source: https://observablehq.com/framework/inputs/table This snippet demonstrates how to use Inputs.table to display tabular data with custom formatting for each column. It utilizes a sparkbar function to visualize maximum values and applies a string transformation to the 'sex' column. This approach is useful for enhancing data readability within tables. ```javascript Inputs.table(penguins, { format: { culmen_length_mm: sparkbar(d3.max(penguins, d => d.culmen_length_mm)), culmen_depth_mm: sparkbar(d3.max(penguins, d => d.culmen_depth_mm)), flipper_length_mm: sparkbar(d3.max(penguins, d => d.flipper_length_mm)), body_mass_g: sparkbar(d3.max(penguins, d => d.body_mass_g)), sex: (x) => x.toLowerCase() } }) ``` -------------------------------- ### Create a Checkbox Input (JavaScript) Source: https://observablehq.com/framework/inputs/index Creates a checkbox input component using Observable Inputs. It allows users to select multiple options from a predefined list. Options like 'disabled', 'sort', 'unique', and 'value' can customize its behavior and appearance. The input's generated value is exposed as a reactive variable. ```javascript const checkout = view( Inputs.checkbox(["B", "A", "Z", "Z", "⚠️F", "D", "G", "G", "G", "⚠️Q"], { disabled: ["⚠️F", "⚠️Q"], sort: true, unique: true, value: "B", label: "Choose categories:" }) ); ``` -------------------------------- ### Create Select with Map and Custom Format Function Source: https://observablehq.com/framework/inputs/select This snippet demonstrates creating a select dropdown using a Map where the format function is used to customize the display of each option. The format function receives an array containing the key and value from the Map entry. The selection is stored in 'size2'. ```javascript const size2 = view( Inputs.select( new Map([ ["Short", 8], ["Tall", 12], ["Grande", 16], ["Venti", 20] ]), {value: 12, label: "Size", format: ([name, value]) => `${name} (${value} oz)`} ) ); ``` -------------------------------- ### Visualize Data with Plot.js Scatter Plot Source: https://observablehq.com/framework/inputs/index Generates a scatter plot using Plot.js to visualize athlete data, specifically 'weight' vs. 'height'. It highlights athletes belonging to a selected sport in red, allowing for direct comparison within the context of a chosen sport. ```javascript Plot.plot({ title: `How ${sport} athletes compare`, marks: [ Plot.dot(olympians, {x: "weight", y: "height"}), Plot.dot(olympians.filter((d) => d.sport === sport), {x: "weight", y: "height", stroke: "red"}) ] }) ``` -------------------------------- ### Use HTML for Text Input Label Styling Source: https://observablehq.com/framework/inputs/text Illustrates how to use HTML elements, like ``, for the label of a text input to achieve custom styling. This allows for more control over the label's appearance. ```javascript const signature = view( Inputs.text({ label: html`Fancy`, placeholder: "What’s your fancy?" }) ); ``` -------------------------------- ### Display Table with Sortable Columns Source: https://observablehq.com/framework/inputs/index Renders a data table where users can sort columns by clicking on their headers. The sort order is temporary and resets on page reload. Persistence can be achieved by specifying the sort option. ```javascript Inputs.table(searchResults) ``` -------------------------------- ### JavaScript Range Input for Weight Filtering Source: https://observablehq.com/framework/inputs/index This snippet shows how to create a range input slider for selecting a target weight in kilograms. It uses Observable Inputs and D3.js to define the slider's range based on the extent of weight data and sets a step value and label. The output is a view object representing the interactive slider. ```javascript const weight = view( Inputs.range( d3.extent(olympians, (d) => d.weight), {step: 1, label: "weight (kg)"} ) ); ``` -------------------------------- ### Range Input with Label and Placeholder Source: https://observablehq.com/framework/inputs/range Adds a descriptive label and an optional placeholder to the range input. The placeholder is visible when the number input is empty. ```javascript const gain = view(Inputs.range([0, 11], {label: "Gain", step: 0.1, placeholder: "0–11"})); ``` -------------------------------- ### Basic Textarea Input (JavaScript) Source: https://observablehq.com/framework/inputs/textarea Creates a basic textarea input element. The value is an empty string by default and updates as the user types. No external libraries are required beyond Observable Inputs. ```javascript const text = view(Inputs.textarea()); ``` -------------------------------- ### Display Grouped Data Table Source: https://observablehq.com/framework/inputs/index Renders a table displaying data that has been grouped by sport. This is typically used in conjunction with a grouped select input to show the details of athletes within a selected sport. ```javascript Inputs.table(sportAthletes) ``` -------------------------------- ### Configure Text Input with Submit Option Source: https://observablehq.com/framework/inputs/text Explains how to use the `submit` option to defer reporting input value changes until the user explicitly submits the form (e.g., by clicking a button or pressing Enter). This is useful for triggering expensive operations. ```javascript const query = view(Inputs.text({label: "Query", placeholder: "Search", submit: true})); ``` -------------------------------- ### Checkbox Input: Basic String Selection Source: https://observablehq.com/framework/inputs/checkbox Creates a checkbox input for selecting multiple string values. The initial value defaults to an empty array. The 'label' option sets the visible label for the input. ```javascript const colors = view(Inputs.checkbox(["red", "green", "blue"], {label: "color"})); ``` -------------------------------- ### Create Selectable Table Input with Observable Inputs Source: https://observablehq.com/framework/inputs/table This snippet demonstrates how to create a table input using Observable's Inputs.table function. It allows users to select rows interactively. The 'required: false' option controls whether an empty selection is permitted when no rows are initially selected. The 'selection' variable will hold the currently selected rows. ```javascript const selection = view(Inputs.table(penguins, { required: false })); selection // Try selecting rows above! ``` -------------------------------- ### Button with No Content Source: https://observablehq.com/framework/inputs/button Creates a button input without any specific content. When no content is provided, the button will display default text or be empty. ```javascript const x = view(Inputs.button()); ``` -------------------------------- ### Create Email Input with Validation Source: https://observablehq.com/framework/inputs/text Shows how to configure a text input specifically for email addresses using the `type: "email"` option. The browser may provide built-in validation for this type. ```javascript const email = view( Inputs.text({ type: "email", label: "Email", placeholder: "Enter your email" }) ); ``` -------------------------------- ### Checkbox Input: Map Data with Custom Format Function Source: https://observablehq.com/framework/inputs/checkbox Shows how to use a 'format' function with Map data to customize the display of each option, combining both the key (name) and value (ounces) from the Map entry. ```javascript const size2 = view( Inputs.checkbox( new Map([ ["Short", 8], ["Tall", 12], ["Grande", 16], ["Venti", 20] ]), {value: [12], label: "Size", format: ([name, value]) => `${name} (${value} oz)`} ) ); ``` -------------------------------- ### Create Select with Custom Display and Value Formatting Source: https://observablehq.com/framework/inputs/select This snippet illustrates how to create a select dropdown where the displayed options are formatted to show the team name, but the underlying value is the entire team object. It also demonstrates setting a default selected value using the 'value' option. The selection is stored in the 'favorite' variable. ```javascript const teams = [ {name: "Lakers", location: "Los Angeles, California"}, {name: "Warriors", location: "San Francisco, California"}, {name: "Celtics", location: "Boston, Massachusetts"}, {name: "Nets", location: "New York City, New York"}, {name: "Raptors", location: "Toronto, Ontario"}, ]; const favorite = view( Inputs.select(teams, { label: "Favorite team", format: (t) => t.name, value: teams.find((t) => t.name === "Warriors") }) ); ``` -------------------------------- ### Create Select Input from d3.group Data Source: https://observablehq.com/framework/inputs/select This snippet shows how to create a select input populated with data grouped by sport using d3.group. It initializes a view with a select input, allowing users to choose a sport from the grouped Olympian data. ```javascript const sportAthletes = view( Inputs.select( d3.group(olympians, (d) => d.sport), {label: "Sport"} ) ); ``` -------------------------------- ### Customize Table Input Columns and Headers Source: https://observablehq.com/framework/inputs/table Allows customization of displayed columns and their headers in the table input. The `columns` option specifies which columns to show and their order, while the `header` option allows for custom display names for each column. ```javascript Inputs.table(penguins, { columns: [ "species", "culmen_length_mm", "culmen_depth_mm", "flipper_length_mm" ], header: { species: "Penguin Species", culmen_length_mm: "Culmen length (mm)", flipper_length_mm: "Flipper length (mm)", culmen_depth_mm: "Culmen Depth (mm)" } }) ``` -------------------------------- ### Checkbox Input: Object Array with Custom Formatting Source: https://observablehq.com/framework/inputs/checkbox Demonstrates using an array of objects for checkbox options, with a 'format' function to display a specific property ('name') of each object. This allows for more descriptive labels. ```javascript const teams = [ {name: "Lakers", location: "Los Angeles, California"}, {name: "Warriors", location: "San Francisco, California"}, {name: "Celtics", location: "Boston, Massachusetts"}, {name: "Nets", location: "New York City, New York"}, {name: "Raptors", location: "Toronto, Ontario"}, ]; const watching = view(Inputs.checkbox(teams, {label: "Watching", format: (x) => x.name})); ``` -------------------------------- ### Radio Input with Array of Objects Source: https://observablehq.com/framework/inputs/radio Shows how to use an array of objects for radio input options. The `format` function is used to extract the `name` property from each object for display. ```javascript const teams = [ {name: "Lakers", location: "Los Angeles, California"}, {name: "Warriors", location: "San Francisco, California"}, {name: "Celtics", location: "Boston, Massachusetts"}, {name: "Nets", location: "New York City, New York"}, {name: "Raptors", location: "Toronto, Ontario"}, ]; const favorite = view(Inputs.radio(teams, {label: "Favorite team", format: x => x.name})); ``` -------------------------------- ### Create Multi-Select Dropdown with Observable Inputs Source: https://observablehq.com/framework/inputs/select This snippet shows how to create a multi-select dropdown using Observable's Inputs.select function. It allows the user to select multiple options from a predefined list of colors. The selected values are stored in the 'fewerColors' variable. ```javascript const fewerColors = view(Inputs.select(x11colors, {multiple: 4, label: "Favorite colors"})); ``` -------------------------------- ### Create a date input with explicit submission Source: https://observablehq.com/framework/inputs/date Demonstrates using the `submit: true` option to defer input value reporting until the user explicitly submits it via a button or Enter key. The `submit` option can also customize the submit button's text or HTML content. ```javascript const sdate = view(Inputs.date({label: "Date", submit: true})); ``` -------------------------------- ### Checkbox Input: String Data with Sorting and Unique Options Source: https://observablehq.com/framework/inputs/checkbox Demonstrates creating a checkbox from a string, using 'sort' to alphabetize the options and 'unique' to remove duplicate characters. The initial value is an empty array by default. ```javascript const bases = view(Inputs.checkbox("GATTACA", {sort: true, unique: true})); ``` -------------------------------- ### Textarea Input with Submission Option (JavaScript) Source: https://observablehq.com/framework/inputs/textarea Configures a textarea input where changes are only reported upon explicit submission (e.g., clicking a button or pressing Command-Enter). This is useful for deferring expensive operations. ```javascript const essay = view(Inputs.textarea({label: "Essay", rows: 6, minlength: 40, submit: true})); ``` -------------------------------- ### Create Toggle Input with Custom Values (JavaScript) Source: https://observablehq.com/framework/inputs/toggle Shows how to define custom values for the toggle input using the 'values' option. This allows toggling between any two values, not just true/false. The default values are [true, false]. ```javascript const binary = view(Inputs.toggle({label: "Binary", values: [1, 0]})); ``` -------------------------------- ### Selecting specific rows from data using map and array indices Source: https://observablehq.com/framework/inputs/table This JavaScript code snippet demonstrates how to select specific items from an array of data (penguins) using the `map` function and an array of indices. It's useful for pre-selecting rows in a table. ```javascript [1, 3, 7, 9].map((i) => penguins[i]) ``` -------------------------------- ### Custom Button Value and Reduction Source: https://observablehq.com/framework/inputs/button Configures a button with custom initial value and a reduction function. The button labeled 'Update' is initialized with `null` and its value is updated to the current date (`new Date()`) each time it is clicked. ```javascript const time = view(Inputs.button("Update", {value: null, reduce: () => new Date})); ``` -------------------------------- ### Conditional Text Based on Button Click Source: https://observablehq.com/framework/inputs/button Displays different text messages based on the state of a confirmation button. If the 'OK' button (labeled 'Continue?') is clicked, it shows 'Confirmed!'; otherwise, it shows 'Awaiting confirmation…'. ```javascript confirm ? "Confirmed!" : "Awaiting confirmation…" ``` -------------------------------- ### Radio Input Allowing Null Selection Source: https://observablehq.com/framework/inputs/radio Demonstrates a radio input that allows the user to select 'Yea', 'Nay', or no option (represented by null). The `format` option is used to display 'Abstain' when null is selected. ```javascript const vote = view(Inputs.radio(["Yea", "Nay", null], {value: null, format: (x) => x ?? "Abstain"})); ``` -------------------------------- ### Create Single Select Input with Default Value Source: https://observablehq.com/framework/inputs/select This snippet demonstrates how to create a single-value select input using Observable Inputs. It allows the user to select a favorite color from a predefined list (x11colors) and sets the initial default value to 'steelblue'. ```javascript const color = view(Inputs.select(x11colors, {value: "steelblue", label: "Favorite color"})); ``` -------------------------------- ### Range Input with TeX Label Source: https://observablehq.com/framework/inputs/range Employs TeX notation for the label of the range input, suitable for mathematical or scientific contexts. ```javascript const psir = view(Inputs.range([0, 1], {label: tex`\psi(\textbf{r})`})); ``` -------------------------------- ### Create a read-only date input Source: https://observablehq.com/framework/inputs/date Shows how to set a date input to read-only mode using the `readonly: true` option. This allows the input to be displayed with its value but prevents any changes by the user. ```javascript const readonly = view(Inputs.date({label: "Readonly date", value: "2021-01-01", readonly: true})); ``` -------------------------------- ### Range Input with Step and Extent Source: https://observablehq.com/framework/inputs/range Configures a range input with a specified minimum and maximum value, and a step value to control precision. This is useful for setting integer ranges or specific decimal precision. The up/down buttons in the number input only work if a step is specified. ```javascript const y = view(Inputs.range([0, 255], {step: 1})); ``` -------------------------------- ### CSV File Input with Validation Source: https://observablehq.com/framework/inputs/file Creates a file input specifically for CSV files. It includes a label, accepts only .csv files, and requires a file to be selected before the input resolves. The selected CSV file can then be parsed. ```javascript const csvfile = view(Inputs.file({label: "CSV file", accept: ".csv", required: true})); // Parse the selected CSV file with typed values csvfile.csv({typed: true}) ``` -------------------------------- ### Range Input with HTML Label Source: https://observablehq.com/framework/inputs/range Utilizes an HTML element for the label of the range input, allowing for richer text formatting and styling. ```javascript const n = view(Inputs.range([1, 10], {label: html`Top n`, step: 1})); ``` -------------------------------- ### Create a Click-Counting Button Source: https://observablehq.com/framework/inputs/button Generates a button labeled 'Click me' that counts the number of times it has been clicked. The button's value increments by default on each click. The current click count is displayed below the button. ```javascript const clicks = view(Inputs.button("Click me")); clicks ``` -------------------------------- ### JavaScript Table Filtering with Range Input Source: https://observablehq.com/framework/inputs/index This snippet demonstrates how to filter a table of Olympian data based on the selected weight from a range input. It uses the `weight` variable (presumably an input range) to filter rows where the athlete's weight is within 10% of the target weight. The filtered data is then displayed in a sortable table using Observable Inputs. ```javascript Inputs.table( olympians.filter((d) => d.weight < weight * 1.1 && weight * 0.9 < d.weight), {sort: "weight"} ) ``` -------------------------------- ### Multiple Buttons for Counter Control Source: https://observablehq.com/framework/inputs/button Implements a counter with three buttons: 'Increment', 'Decrement', and 'Reset'. Each button is associated with a specific reduction function to modify the counter's value, which is initialized to 0. ```javascript const counter = view(Inputs.button([ ["Increment", value => value + 1], ["Decrement", value => value - 1], ["Reset", value => 0] ], {value: 0, label: "Counter"})); counter ``` -------------------------------- ### Display Tabular Data with Table Input Source: https://observablehq.com/framework/inputs/table Renders tabular data using the table input component. By default, all columns are visible and a subset of rows are initially displayed, with more rows revealed upon scrolling. Column headers remain fixed for better readability. ```javascript Inputs.table(penguins) ``` -------------------------------- ### Format Table Columns with Custom Functions in Observable Source: https://observablehq.com/framework/inputs/table This code illustrates how to customize the display of data within a table input using the 'format' option. It specifies custom formatting functions for 'culmen_length_mm', 'culmen_depth_mm', and 'sex' columns to control their appearance in the table. For instance, 'culmen_length_mm' and 'culmen_depth_mm' are formatted to one decimal place, and 'sex' is abbreviated. ```javascript Inputs.table(penguins, { format: { culmen_length_mm: (x) => x.toFixed(1), culmen_depth_mm: (x) => x.toFixed(1), sex: (x) => x === "MALE" ? "M" : x === "FEMALE" ? "F" : "" } }) ``` -------------------------------- ### Radio Input with Sorting and Unique Options Source: https://observablehq.com/framework/inputs/radio Shows how to sort the radio input keys and ensure only unique keys are displayed using the `sort` and `unique` options. This is useful for datasets with repeated or unsorted keys. ```javascript const base = view(Inputs.radio("GATTACA", {sort: true, unique: true})); ``` -------------------------------- ### Create Disabled Toggle Input (JavaScript) Source: https://observablehq.com/framework/inputs/toggle Demonstrates how to disable a toggle input, preventing the user from changing its value. This is useful for displaying a setting that cannot be modified by the user. ```javascript const frozen = view(Inputs.toggle({label: "Frozen", value: true, disabled: true})); ``` -------------------------------- ### Basic Range Input Source: https://observablehq.com/framework/inputs/range Creates a basic range input with default settings. It defaults to a floating-point number between 0 and 1 with full precision. The value is initially set to the middle of the range (0.5). ```javascript const x = view(Inputs.range()); ``` -------------------------------- ### Filter Data with a Select Input for Sport Source: https://observablehq.com/framework/inputs/index Creates a dropdown select input to filter data based on the 'sport' column. It displays only unique sport values, sorted alphabetically. The input's value is used to filter an array, typically for further visualization or display. ```javascript const sport = view( Inputs.select( olympians.filter((d) => d.weight && d.height).map((d) => d.sport), {sort: true, unique: true, label: "sport"} ) ); ``` -------------------------------- ### Create Disabled Text Input Source: https://observablehq.com/framework/inputs/text Illustrates how to create a text input whose value cannot be changed by the user. The `disabled: true` option makes the input read-only and visually distinct. ```javascript const fixed = view(Inputs.text({label: "Fixed value", value: "Can’t edit me!", disabled: true})); ``` -------------------------------- ### Checkbox Input: d3.group Data with Sorting and Initial Keys Source: https://observablehq.com/framework/inputs/checkbox Utilizes d3.group to structure data for the checkbox, allowing selection based on grouped criteria (e.g., gold medal count). Options like 'sort' and 'key' control the order and initial selection. ```javascript const goldAthletes = view( Inputs.checkbox( d3.group(olympians, (d) => d.gold), {label: "Gold medal count", sort: "descending", key: [4, 5]} ) ); ``` -------------------------------- ### Create a required date input Source: https://observablehq.com/framework/inputs/date Illustrates how to make a date input mandatory using the `required: true` option. If `required` is true, the initial value is `undefined` instead of `null`, causing dependent cells to wait for a valid input. ```javascript const rdate = view(Inputs.date({label: "Date", required: true})); ``` -------------------------------- ### Range Input with Logarithmic Transform Source: https://observablehq.com/framework/inputs/range Applies a logarithmic transform to the range input, enabling non-linear slider behavior suitable for log-distributed values. The Math.log function is used for the transform. ```javascript Inputs.range([1, 100], {transform: Math.log}) ``` -------------------------------- ### Range Input with Square Root Transform Source: https://observablehq.com/framework/inputs/range Applies a square root transform to the range input, providing non-linear slider control. The Math.sqrt function is used for the transform. ```javascript Inputs.range([0, 1], {transform: Math.sqrt}) ``` -------------------------------- ### Radio Input with Disabled Options Source: https://observablehq.com/framework/inputs/radio Illustrates how to disable specific options in a radio input. The `disabled` option can take a boolean to disable all options or an array of values to disable individually. ```javascript const vowel = view(Inputs.radio([...'AEIOUY'], {label: "Vowel", disabled: ["Y"]})); ``` -------------------------------- ### Disabled Color Input Source: https://observablehq.com/framework/inputs/color Shows how to disable a color input using the `disabled` option. A disabled input cannot be changed by the user, but its value can still be programmatically set. The `readonly` property is not supported. ```javascript const disabled = view(Inputs.color({label: "Disabled", value: "#f28e2c", disabled: true})); ``` -------------------------------- ### Checkbox Input: Disabling Specific Options Source: https://observablehq.com/framework/inputs/checkbox Shows how to disable specific checkbox options by providing an array of their values to the 'disabled' option. This prevents users from selecting these particular choices. ```javascript const vowels = view(Inputs.checkbox([...'AEIOUY'], {label: "Vowel", disabled: ["Y"]})); ``` -------------------------------- ### Filter Data with Grouped Select Input Source: https://observablehq.com/framework/inputs/index Implements a select input populated with data grouped by sport using d3.group. This allows users to select a sport and view all associated athletes. The input sorts the sport keys alphabetically, and its value represents the data for the selected group. ```javascript const sportAthletes = view( Inputs.select( d3.group(olympians, (d) => d.sport), {sort: true, label: "sport"} ) ); ``` -------------------------------- ### Radio Input with Grouped Data (d3.group) Source: https://observablehq.com/framework/inputs/radio Demonstrates using a Map generated by `d3.group` as data for a radio input. This allows selecting based on grouped data, such as gold medal counts for Olympians. ```javascript const goldAthletes = view( Inputs.radio( d3.group(olympians, (d) => d.gold), {label: "Gold medal count", sort: "descending"} ) ); ``` -------------------------------- ### Range Input with Custom Formatting Source: https://observablehq.com/framework/inputs/range Specifies a custom function to format the displayed number in the range input. The format function must return a string compatible with native number parsing. Here, it formats to two decimal places. ```javascript const f = view(Inputs.range([0, 1], {format: x => x.toFixed(2)})); ``` -------------------------------- ### Display Click Count Source: https://observablehq.com/framework/inputs/button Displays a message indicating the number of times a button has been clicked. This utilizes the `clicks` variable, which holds the current count from the associated button input. ```javascript You have clicked ${clicks} times. ``` -------------------------------- ### Disable Entire Select Input Source: https://observablehq.com/framework/inputs/select This code illustrates how to disable all options within a select input. The `disabled: true` option is passed to the select input, making it non-interactive for the user. ```javascript Inputs.select(["A", "E", "I", "O", "U", "Y"], {label: "Vowel", disabled: true}) ``` -------------------------------- ### Sort Tabular Data in Table Input Source: https://observablehq.com/framework/inputs/table Enables sorting of tabular data within the table input component. The `sort` option specifies the column to sort by, and the `reverse` option can be set to `true` for descending order. Undefined values are placed at the end. ```javascript Inputs.table(penguins, {sort: "body_mass_g", reverse: true}) ```