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.
Created
November 26, 2021 17:42
-
-
Save marijn/49de73e88aa60713ecf1fd662c48e33d to your computer and use it in GitHub Desktop.
Replace numeric input element with select element on mobile devices
This file contains 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 characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternative approach from the same era: Replace the
number
fortel
.