vanilla js automatic dash

info

2023-01-01

mi

input be like Muster XX-XXXX-XXXX-XXXX


<input type="text" maxlength="22" id="22SERIAL">


document.getElementById('22SERIAL').addEventListener('keyup', function (e) {
	var value = this.value;
	if (value.length < 22) {
		if (value.length == 2) {
			this.value = this.value + '-';
		}
		else if (value.length == 7) {
			this.value = this.value + '-';
		}
		else if (value.length == 12) {
			this.value = this.value + '-';
		}
		else if (value.length == 17) {
			this.value = this.value + '-';
		}
	}
	console.log(this.value);
}, false);			


OR you do this

<div class="row"> 
  <div class="column"><input type="text" maxlength="2" size="2" id="ssn_1"></div> 
  <div class="column"><input type="text" maxlength="4" size="4" id="ssn_2"></div> 
  <div class="column"><input type="text" maxlength="4" size="4" id="ssn_3"></div> 
  <div class="column"><input type="text" maxlength="4" size="4" id="ssn_4"></div> 
  <div class="column"><input type="text" maxlength="4" size="4" id="ssn_5"></div> 
</div>
           
var downStrokeField; 
function autojump(fieldName,nextFieldName,fakeMaxLength){  
   var myForm = document.forms[document.forms.length - 1]; 
   var myField = myForm.elements[fieldName];
   myField.nextField=myForm.elements[nextFieldName]; 
   if (myField.maxLength == null){ 
        myField.maxLength=fakeMaxLength; 
        myField.onkeydown=autojump_keyDown; 
      myField.onkeyup=autojump_keyUp;  
      var myValue = document.getElementById(fieldName).value; 
    console.log('myValue:'); console.log(myValue); 
  }  

function autojump_keyDown(){ 
  this.beforeLength=this.value.length; downStrokeField=this; 
} 
function autojump_keyUp(){ 
  if ( (this == downStrokeField) && (this.value.length > this.beforeLength) && (this.value.length >= this.maxLength) ) this.nextField.focus(); 
    downStrokeField=null; 
}

autojump('ssn_1', 'ssn_2', 2);
autojump('ssn_2', 'ssn_3', 4);
autojump('ssn_3', 'ssn_4', 4);
autojump('ssn_4', 'ssn_5', 4);

function join_names() {
	var ssn_1 = document.getElementById('ssn_1').value;
	var ssn_2 = document.getElementById('ssn_2').value;
	var ssn_3 = document.getElementById('ssn_3').value;
	var ssn_4 = document.getElementById('ssn_4').value;
	var ssn_5 = document.getElementById('ssn_5').value;
	var SN = [ssn_1,ssn_2,ssn_3,ssn_4,ssn_5].join('-');
	console.log(ssn_1);
	console.log(ssn_2);
	console.log(ssn_3);
	console.log(ssn_4);
	console.log(ssn_5);
	console.log(SN);
	//document.write("Eingabe: " + SN + ",");
	}