Skip to content

Instantly share code, notes, and snippets.

@marijn
Created November 26, 2021 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marijn/49de73e88aa60713ecf1fd662c48e33d to your computer and use it in GitHub Desktop.
Save marijn/49de73e88aa60713ecf1fd662c48e33d to your computer and use it in GitHub Desktop.
Replace numeric input element with select element on mobile devices

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.

<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>
@marijn
Copy link
Author

marijn commented Nov 26, 2021

Alternative approach from the same era: Replace the number for tel.

document.addEventListener('DOMContentLoaded', function () {
    if ('ontouchstart' in document.documentElement) {
        var numericInputs = document.querySelectorAll('input[type="number"]');

        for (var i = 0, nrOfNumericInputs = numericInputs.length, input; i < nrOfNumericInputs; i++) {
            input = numericInputs.item(i);
            input.type = 'tel';
        }
    }
}, false);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment