Search code examples
javascriptangularjsangularjs-ng-options

document.getElementById("").value returns object instead value


I have an data in below given format

{
 USA: { 
    CA: { 'SAN FRANCISCO':['94188', '94158', '94143'] },
    LA: { 'BATON ROUGE':['70898','70895','70891'] }
  }
} 

trying to add them to dependent drop downs namely Country, State, City and Zip code. I'm using ng-option but while getting the value for country dropdown its returning oject:16 instead of value.

$scope.countries = {
    USA: { 
       CA: { 'SAN FRANCISCO':['94188', '94158', '94143'] },
       LA: { 'BATON ROUGE':['70898','70895','70891'] }
    }
}

$scope.GetSelectedCountry = function () {
    $scope.strCountry = document.getElementById("country").value;
}  

<b>Country:</b>
&nbsp;
<select id="country" ng-model="statessource" ng-disabled="!type" ng-options="country for (country, states) in countries" ng-change="GetSelectedCountry()">
<option value=''>Select Country</option> 


Solution

  • You have used an ng-model variable for your select tag, but you have not used that in your controller to get the selected value. There is no need to access the value using javascript dom selector, instead you can directly use the model value of the select tag $scope.statessource.

    <!DOCTYPE html>
    <html>
    
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    
        <script>
            var app = angular.module('myApp', []);
            app.controller('myCtrl', function ($scope) {
                $scope.countries = {
                    USA: {
                        CA: {
                            'SAN FRANCISCO': ['94188', '94158', '94143']
                        },
                        LA: {
                            'BATON ROUGE': ['70898', '70895', '70891']
                        }
                    }
                }
    
                $scope.GetSelectedCountry = function () {
                    $scope.strCountry = $scope.statessource;
                    console.log($scope.strCountry);
                }
            });
        </script>
    </head>
    
    <body ng-app="myApp" ng-controller="myCtrl">
    
        <b>Country:</b> &nbsp;
        <select id="country" ng-model="statessource" ng-options="country for (country, states) in countries" ng-change="GetSelectedCountry()">
            <option value=''>Select Country</option>
        </select>
    
    </body>
    
    </html>