Created
November 26, 2021 17:42
-
-
Save marijn/49de73e88aa60713ecf1fd662c48e33d to your computer and use it in GitHub Desktop.
Revisions
-
marijn created this gist
Nov 26, 2021 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1 @@ Something I wrote years ago but might still be useful. A simple script to replace numeric `input` elements with their equivalent `select` element to ease input on touch based devices. This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,57 @@ <input name="my_numeric_input" type="number" min="2" max="3" data-custom-property="custom-value" /> <script> document.addEventListener('DOMContentLoaded', function (domLoaded) { var document = domLoaded.target; function replaceNumericInputWithSelectList (inputElement) { var name = inputElement.name; var min = inputElement.min; var max = inputElement.max; var value = undefined === inputElement ? undefined : parseInt(inputElement.value); if (!name) { throw new Error('Name attribute is missing.'); } else if (!min) { throw new Error('Minimum value missing.'); } else if (!max) { throw new Error('Maximum missing.'); } var selectElement = document.createElement('select'); selectElement.setAttribute('name', name); anEmptyOptionElement = document.createElement('option'); selectElement.appendChild(anEmptyOptionElement); for (var i = min, anOptionElement; i <= max; i++) { anOptionElement = document.createElement('option'); anOptionElement.setAttribute('value', i); anOptionElement.selected = (value === i); anOptionElement.textContent = i; selectElement.appendChild(anOptionElement); } selectElement.dataset = inputElement.dataset.entries(); inputElement.parentNode.replaceChild(selectElement, inputElement); } if ('ontouchstart' in document.documentElement) { var numericInputs = document.querySelectorAll('input[type="number"]'); for (var i = 0, nrOfNumericInputs = numericInputs.length, anInput; i < nrOfNumericInputs; i++) { anInput = numericInputs.item(i); try { replaceNumericInputWithSelectList(anInput); } catch (anError) { if (window.console && window.console.error) { window.console.error(anError.message); } } } } }, false); </script>