Dylan Buth
Dylan Buth

Reputation: 1666

Adding to Javascript array based on if statement

I am needing to add error messages to an array based on the outcome of if statements. The code below brings back the second error message only when I input data that should trigger both. I know that .push() does not just add on to the previous array but the only way they had to fix that was making a for loop. I think there is some simple function somewhere I am just missing.

    $scope.error = {};
    if ($password == null || $vPassword == null || $email == null || $vEmail == null) {
        console.log('All fields must be filled in');
    } else {
        if ($scope.verifyPassword !== $scope.password) {
            $scope.error[scope.error.length()] = 'Your passwords must match...';
        }
        if ($scope.verifyEmail !== $scope.email) {
            $scope.error.push = ['Your email addresses must match...'];
        }
        console.log($scope.error);
    }

I think the code is pretty self-explanatory. Let me know if you need any more info.

Thanks!

edit: I'm not sure what code produced the error I explained. Sorry. The code above was crap code I was messing with trying to get it to work. Obviously most of it doesn't make sense. The accepted answer was what I originally thought was producing that error but evidently it works. Sorry for the crappy post.

Upvotes: 0

Views: 70

Answers (2)

helllomatt
helllomatt

Reputation: 1339

You need to change $scope.error into an array, not an object, then .push() will work appropriately.

$scope.error = [];
$scope.error.push("Your passwords must match...");

console.log($scope.error);

Produces

["Your passwords must match..."]

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

push is a function and should be invoked using ().

$scope.error.push('Your email addresses must match...');

Also, you cannot invoke push on an object that is not an Array. You must instantiate $scope.error as an Array:

$scope.error = [];

Upvotes: 3

Related Questions