Skip to content

Instantly share code, notes, and snippets.

@marijn
Created November 26, 2021 17:42
Show Gist options
  • Select an option

  • Save marijn/49de73e88aa60713ecf1fd662c48e33d to your computer and use it in GitHub Desktop.

Select an option

Save marijn/49de73e88aa60713ecf1fd662c48e33d to your computer and use it in GitHub Desktop.

Revisions

  1. marijn created this gist Nov 26, 2021.
    1 change: 1 addition & 0 deletions README.markdown
    Original 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.
    57 changes: 57 additions & 0 deletions example.html
    Original 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>