When button clicked on load it adds 'undefined' to array

115 views Asked by At

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.

example

3

There are 3 answers

3
MD Hasan Patwary On BEST ANSWER

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:

handleSubmit() {
    if (typeof this.studentName !== 'undefined') {
        var name = String(this.studentName).trim();
        this.currentStudentName = name;

        if (this.currentStudentName === '') {
            alert('Empty entry!');
        } else if (this.listOfNames.includes(this.currentStudentName)) {
            alert('Duplicate name found!');
        } else {
            this.listOfNames.push(this.currentStudentName);
        }
    } else {
        alert('Name is undefined!');
    }
}
2
Kaushal Joshi On

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):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Name List (Card Format)</title>
    <style>
        .student-card {
            display: inline-block; /* Display cards horizontally */
            margin: 10px; /* Add margin for spacing */
            padding: 10px; /* Add padding for content */
            border: 1px solid #ddd; /* Add a border */
            border-radius: 5px; /* Add rounded corners */
            background-color: #eee; /* Optional: Add a background color */
            text-align: center; /* Center the content within the card */
        }
    </style>
</head>
<body>
    <h1>Add Students</h1>
    <form id="studentForm" aria-label="Student name submission form">
        <label for="studentName">Student Name:</label>
        <input type="text" id="studentName" name="studentName" placeholder="Enter student name" aria-required="true">
        <button type="submit">Add Student</button>
    </form>
    <br>
    <div id="studentList">Student List:</div>
    <script src="script.js"></script>
</body>
</html>

JavaScript (script.js):

// Get references to form elements
const studentForm = document.getElementById('studentForm');
const studentNameInput = document.getElementById('studentName');
const studentList = document.getElementById('studentList');

// Initialize an empty array to store student names
let listOfNames = [];

function validateName(name) {
  // Basic validation (example: check for minimum length)
  return name.trim().length >= 2;
}

studentForm.addEventListener('submit', function(event) {
  event.preventDefault(); // Prevent default form submission

  // Get the entered name, trimmed and converted to string
  const name = String(studentNameInput.value).trim();

  if (validateName(name)) {
    if (!listOfNames.includes(name)) {
      listOfNames.push(name);
      // Create and append a student card element dynamically
      const studentCard = document.createElement('div');
      studentCard.className = 'student-card';
      studentCard.textContent = name;
      studentList.appendChild(studentCard);
    } else {
      alert('Duplicate name found!');
    }
  } else {
    alert('Invalid name! Please enter a name with at least 2 characters.');
  }

  // Clear the input field for next entry
  studentNameInput.value = '';
});

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

1
Aniket Gund On

You have to just update your condition your second if

else if (this.currentStudentName === '' || this.currentStudentName == "undefined") {
    alert('Emptry entry!');
}