I am trying to generate a input value based on 2 earlier input values the user filled in. First is a name, the second one is a date. Now I need to concat and format these 2 values and set them for another input.
This is what I already come up with:
- Event listener for first input: Name
- Format the Name value
- Event listener for second input: Date
- Format the Date value
- Concat these 2 values
- Set the concat value in third input
The code I have so far:
window.onload = function () {
/* event listener for first input: Name */
document.getElementById('input_7_1').addEventListener('change', formatTitle);
/* function to format the name value properly */
function formatTitle(){
document.getElementById('input_7_1').addEventListener("input", function(){
var title = document.getElementById('input_7_1').value;
var formatTitle = title.replace(/\s /g, '');
});
}
/* event listener for second input: Date */
document.getElementById('input_7_3').addEventListener('change', formatDate);
/* function to format the date value properly */
function formatDate(){
document.getElementById('input_7_3').addEventListener("input", function(){
var date = document.getElementById('input_7_3').value.replace(/\//g, '');
var formatDate = date.slice(0, -4);
});
}
/* concat both values in a variable */
var studentNummer = formatTitle.concat(formatDate);
/* set value in the third input: Studentnummer */
function generateInput(){
document.getElementById('input_7_9').value = studentNummer;
}
}
I am almost there for my feeling. What am I missing here?
CodePudding user response:
I've simplified your code and made it much more understandable. Try this
window.onload = function () {
let studentNoField = document.getElementById('input_7_9');
let enteredDetails = {name: '', date: ''};
/* set value in the third input: Studentnummer */
function generateInput(){
let studentNumber = Object.values(enteredDetails).join('');
studentNoField.value = studentNumber;
}
/* event listener for first input: Name */
document.getElementById('input_7_1').addEventListener('input', function(event){
enteredDetails.name = event.target.value.replace(/\s /g, '');
generateInput();
});
/* event listener for second input: Date */
document.getElementById('input_7_3').addEventListener('input', function(event){
enteredDetails.date = event.target.value.slice(0, -4);
generateInput();
});
}