Home > database >  set maxlength value dynamically in html
set maxlength value dynamically in html

Time:07-07

I have input field, with maxlength = 6 and ng-pattern="/^[0-9]{1,6}$/" accepting only numeric values. On on-blur event I'm formatting the 6 digit code ("123456") to "12-34-56" and browser remembers the formatted value i.e. 12-34-56

next time when I try to auto fill the field using remembered data by browser, enter image description here it only fill 4 digits. How can I fill all the 6 digits. I tried to set the maxlength = 8 when text contains -, but it didn't help.

CodePudding user response:

I prefer solving this kind of issue by rethinking task.

Instead of changing maxLength attribute, change input format. It would be better if user can enter data in "40-15-15" format.

CodePudding user response:

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" />

  • Related