So I’m trying to make a form that accepts names.
The input field will take in a name. When you press the submit button it will add the name to an array only if
name!=null
and- and the name is not a duplicate
after that the array will be displayed below the input box.
For checking the input before adding to the array I used the following code:
var name = String(this.studentName);
name = name.trim();
this.currentStudentName = name;
if (this.listOfNames.includes(this.currentStudentName)) {
alert('Duplicate name found!');
} else if (this.currentStudentName === '') {
alert('Emptry entry!');
} else {
this.listOfNames.push(this.currentStudentName);
}
}
The code is working fine with duplicate values and empty values BUT
If on loading the page if I directly press the submit button, undefined is added to the array and the array is displayed with first entry as "undefined", but
I do not want the undefined to be saved into the array.
3
Answers
To avoid adding undefined to the array when the page loads, you need to handle that case separately. You can add a condition to check if the input is not undefined before adding it to the array. Here’s modified code:
Here’s a complete solution with HTML and JavaScript that addresses the issue of "undefined" being added to the array when the submit button is pressed on page load:
HTML (index.html):
JavaScript (script.js):
Explanation:
Combined Trimming and Conversion: The code combines trimming and
converting to a string in a single line (const name =
String(studentNameInput.value).trim();) for efficiency
Explicit Check for Non-Empty String: The if statement explicitly
checks if name is not an empty string (name !== ”) before further
processing. This prevents "undefined" from being added to the array.
Simplified Conditional: The code uses a single if statement with a
negated condition (!listOfNames.includes(name)) for clarity and
brevity.
Dynamic List Update: The student list is dynamically updated using
innerHTML after a valid name is added.
Error Handling: Alerts are displayed for empty entries and duplicate
names.
Clear Input Field: The input field is cleared after submission for
the next entry.
Additional Considerations:
You might consider setting a default empty value for the input field
to guide the user and further prevent "undefined" submissions.
Implement proper error handling to gracefully handle unexpected input
or other potential issues.
You could add further validation, such as checking for valid name
formats or character lengths.
This code effectively addresses the "undefined" issue and provides a robust solution for managing student names in the list.
Here I’m attaching the output of the code.
Click Here
You have to just update your condition your second if