Search code examples
javascripthtmlapex

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


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


Solution

  • 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!');
        }
    }