How can I limit possible inputs in a HTML5 “number” element?

前端 未结 26 2919
感动是毒
感动是毒 2020-11-22 05:12

For element, maxlength is not working. How can I restrict the maxlength for that number element?

26条回答
  •  离开以前
    2020-11-22 05:33

    Another option is to just add a listener for anything with the maxlength attribute and add the slice value to that. Assuming the user doesn't want to use a function inside every event related to the input. Here's a code snippet. Ignore the CSS and HTML code, the JavaScript is what matters.

    // Reusable Function to Enforce MaxLength
    function enforce_maxlength(event) {
      var t = event.target;
      if (t.hasAttribute('maxlength')) {
        t.value = t.value.slice(0, t.getAttribute('maxlength'));
      }
    }
    
    // Global Listener for anything with an maxlength attribute.
    // I put the listener on the body, put it on whatever.
    document.body.addEventListener('input', enforce_maxlength);
    label { margin: 10px; font-size: 16px; display: block }
    input { margin: 0 10px 10px; padding: 5px; font-size: 24px; width: 100px }
    span { margin: 0 10px 10px; display: block; font-size: 12px; color: #666 }
    
    
    set to 5 maxlength
    
    
    set to 2 maxlength, min 0 and max 99

提交回复
热议问题