【问题标题】:set maxlength value dynamically in html在 html 中动态设置 maxlength 值
【发布时间】:2022-07-06 17:38:45
【问题描述】:

我有输入字段,maxlength = 6ng-pattern="/^[0-9]{1,6}$/" 只接受数值。 在模糊事件中,我将 6 位代码(“123456”)格式化为“12-34-56”,浏览器会记住格式化的值,即 12-34-56

下次当我尝试使用浏览器记住的数据自动填充字段时, 它只填充4位数字。 如何填写所有 6 位数字。我尝试在文本包含 - 时设置maxlength = 8,但没有帮助。

【问题讨论】:

    标签: javascript html jquery angularjs input


    【解决方案1】:

    我更喜欢通过重新思考任务来解决这类问题。

    不要改变 maxLength 属性,而是改变输入格式。如果用户可以输入“40-15-15”格式的数据会更好。

    【讨论】:

      【解决方案2】:

      var part1 = document.querySelector("#part1")
      var part2 = document.querySelector("#part2")
      var part3 = document.querySelector("#part3")
      
      
      part1.onkeyup = function(el) {
      
        if(isNaN(el.key) && el.key !== "Backspace") {
          part1.value = part1.value.slice(0, -1)
        }
      
        if (part1.value.length === 2) {
          part2.focus()
        }
        
      console.log(part1.value + part2.value + part3.value)
      }
      
      part2.onkeyup = function(el) {
      
        if(isNaN(el.key) && el.key !== "Backspace") {
          part2.value = part2.value.slice(0, -1)
        }
      
        if (part2.value.length === 0 && el.key === "Backspace") {
          part1.focus()
        }
        
        if (part2.value.length === 2) {
          part3.focus()
        }
        
      console.log(part1.value + part2.value + part3.value)
      }
      
      part3.onkeyup = function(el) {
      
        if(isNaN(el.key) && el.key !== "Backspace") {
          part3.value = part3.value.slice(0, -1)
        }
      
        if (part3.value.length === 0 && el.key === "Backspace") {
          part2.focus()
        }
      
      console.log(part1.value + part2.value + part3.value)
      }
      input {
        width: 3em;
      }
      <input type="text" id="part1" maxlength="2" /> - 
      <input type="text" id="part2" maxlength="2" /> -
      <input type="text" id="part3" maxlength="2" />

      【讨论】:

        猜你喜欢
        • 2011-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-20
        • 1970-01-01
        相关资源
        最近更新 更多