Updating information within AngularJS select boxes

On my page, I have 3 select boxes. When a user selects an option in the first select box, I want the options in the second select box to update based on the value selected in the first one.

Similarly, I want the options in the third select box to change when an option is selected in the second select box. Any ideas on how to accomplish this efficiently using AngularJS?

Answer №1

To implement this functionality, you can utilize ng-options in combination with Angular filters

Controller

angular.module('app', [])
  .controller('Ctrl', function($scope) {
    $scope.countries = {
      'India': {
        'Andhra Pradesh': ['Vijayawada', 'Guntur', 'Nellore', 'Kadapa'],
        'Madhya Pradesh': ['Hyderabad', 'Warangal', 'Karimnagar'],
      },
      'USA': {
        'San Francisco': ['SOMA', 'Richmond', 'Sunset'],
        'Los Angeles': ['Burbank', 'Hollywood']
      },
      'Australia': {
        'New South Wales': ['Sydney', 'Orange', 'Broken Hill'],
        'Victoria': ['Benalla', 'Melbourne']
      }
    };
  })

Markup

 <div ng-controller="Ctrl">
    <div class="container">>
      <div class="form-group">
        <label class="control-label" for="Country">Country:</label>
        <select class="form-control input-lg" id="country" ng-model="states" ng-options="country for (country, states) in countries">
          <option value=''>Select</option>
        </select>
      </div>
      <div class="form-group">
        <label class="control-label" for="States">States:</label>
        <select class="form-control input-lg" id="state" ng-disabled="!states" ng-model="cities" ng-options="state for (state,city) in states">
          <option value=''>Select</option>
        </select>
      </div>
      <div class="form-group">
        <label class="control-label" for="City">City:</label>
        <select class="form-control input-lg" id="city" ng-disabled="!cities || !states" ng-model="city" ng-options="city for city in cities">
          <option value=''>Select</option>
        </select>
      </div>
    </div>
  </div>

Live Example

Answer №2

To implement the desired functionality, simply utilize the ng-change directive in AngularJS. This directive allows you to invoke a function from your controller to execute any necessary logic.

<select "ng-change"="item_change(selectedItem)" "ng-model"="selectedItem" "ng-options"="item.id as item.name for item in items">

Answer №3

Here is the code snippet in HTML and JavaScript:

<html ng-app="myApp">
<head>
<script src="angular.min.js"></script>
<script src="sct.js"></script>
</head>

<body >
<div ng-controller="MyCtrl">
<select ng-model='selectedNumber' ng-change="adv(selectedNumber);" ng-options='number for number in numbers'></select>
 num:   {{selectedNumber}}
<select ng-model='selected' ng-options="number for number in numbers">   </select>
num:   {{selected}}
<button ng-click="add()" >add</button>
</div>
</body>
</html>

JS:

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope) {    
$scope.numbers = [1,2,3,4,5,6,7,8,9,10];
$scope.num = angular.copy($scope.numbers);
$scope.selectedNumber = $scope.numbers[0];
//$scope.selected = $scope.num[0];

$scope.add=function(){
$scope.num = angular.copy($scope.numbers);
}

$scope.adv = function(selectedNumber){
$scope.num = angular.copy($scope.numbers);
$scope.selected = $scope.numbers[selectedNumber -1]; 
//var a = $scope.num.splice(selectedNumber-1, 1);  
}

$scope.num = angular.copy($scope.numbers);
}); 

I hope this code snippet is useful for you.

Answer №4

Here is the code snippet for countries, states, and cities. This is exactly what you are looking for.

To implement this, create two files: state.php and city.php to output the data in JSON format.

<script type="text/javascript" src="angular.min.js">
    var app = angular.module("placesApp",[]); // Initialize Angular JS App
        app.controller("placesController",["$scope","$http",function($scope,$http){
    $http.get("country.php").success(function(response) // Get Countries from country.php
      {
    $scope.countries = response; // Store the data/response in a variable
      });

    $scope.getStates = function()
            {
                $http.post('state.php',{countryId:$scope.places.country}).success(function(data)
                {
                    $scope.states = data;
                });
            }
    $scope.onStateChange = function()
        {
            $http.post("city.php",{stateId:$scope.places.state}).success(function(data)
            {
                if(data!="")
                {                   
                    $scope.cities = data;
                }
            });
        }

        $scope.submitForm = function()
        {
            $scope.submitted = true;
        }
    }]);
</script>
    <body ng-app="placesApp">
<div ng-controller="placesController">
<form name="placesForm" id="placesForm" method="post" action="">
Countries:<select name="country" id="country" ng-model="places.country" ng-required="true" ng-change="onCountryChange()" ng-options="cou.CountryId as cou.CountryName for cou in countries">
                        <option value="">Select Country</option>
                    </select>
States: <select name="state" id="state" ng-model="places.state" ng-required="true" ng-change="onStateChange()" ng-options="sta.StateId as sta.StateName for sta in states">
                        <option value="" style="display:none;">Select State</option>
                    </select>
Cities:<select name="city" id="city" ng-model="places.city" ng-required="true" ng-options="cit.CityId as cit.CityName for cit in cities">
                        <option value="" style="display:none;">Select City</option>
                    </select>
<input type="submit" name="submit" id="register" value="Submit" ng-click="submitForm()">
</form>
</div>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can parameters be sent without using the .jshintrc file with the gulp-jshint package?

Currently in the process of transitioning a grunt project to a gulp project. In the existing gruntfile, there is a section for the jshint task that looks like this: jshint: { options: { trailing:true, evil:false, indent:4, ...

Troubleshooting Appium error management is ineffective

As a newcomer to appium, I might have made some mistakes. I'm encountering a problem with appium while using wdio and jasmine. it('wtf', (done) => { client.init().element('someName').getText() // ^ here ...

What is the best way to incorporate custom KnockoutJS functions using RequireJS?

I am facing an issue with my View Model that utilizes a custom observableArray function for sorting. The error message I receive states: "...has no methods 'sortByProperty'". How do I go about loading the handlers.js file to resolve this problem ...

Steps for retrieving the currently selected text inside a scrolled DIV

An imperfect DIV with text that requires a scroll bar For example: <div id="text" style='overflow:scroll;width:200px;height:200px'> <div style='font-size:64px;'>BIG TEXT</div> Lorem Ipsum is simply dummy text of th ...

What is the best way to incorporate the :after pseudo-element in JavaScript code

HTML: This is my current code snippet <div class="one"> Apple </div> I am looking to dynamically add the word "juice" using JavaScript with the .style property. Is there an equivalent of :: after in CSS, where I can set the content in JavaS ...

Ensure that PHP errors are reported in JSON format, following the standard content-type guidelines

When working with AngularJs for a single page application that communicates with serverside PHP via JSON, I encountered an issue regarding error reporting from PHP. The PHP header sets JSON, but the error reporting settings are: php_flag display_errors 1 ...

Showing AngularJS information on Views

After successfully implementing static HTML with views, as shown in this example: https://embed.plnkr.co/MJYSP01mz5hMZHlNo2HC/ I am now facing a challenge with integrating the angular-ui accordion within ng-view. You can view the accordion I am attemptin ...

Displaying a message text upon successful AJAX request

I have a web page with an AJAX request that updates data in the database. After the update, I want to display a message to the user on the webpage confirming that the data has been successfully updated. However, currently, no message is being displayed and ...

What is the best way to incorporate visual indicators into specific columns containing certain keywords?

Is there a way to customize the script code responsible for displaying table data so that icons automatically appear next to specific keywords in the Gender column? For instance, can we have an icon like glyphicon glyphicon-heart-empty for Male and glyphic ...

"Encountering an error with ExpressJS where it cannot GET a file, preventing access to other folders' content

My goal is to set up a simple server using expressJS to retrieve data for my Angular application. However, I've encountered an error that says 'Cannot GET/'. This is the code snippet of the webserver I attempted to create: var express = re ...

A guide on successfully handling errors while utilizing S3.getsignedurlpromise() in node.js

I am faced with a challenge in my project involving a node.js server that downloads images from an s3 bucket and serves them to a React client. The issue arises when the wrong file key is sent to the S3 client, as I want to handle this error gracefully by ...

From Python Plotly to JavaScript Plotly - Leveraging the Power of

My primary goal is to avoid using JavaScript and instead focus on analytics. Is it possible for me to create Plotly graphs in Python (for example, in Jupyter notebooks) and then utilize the write_html function to seamlessly integrate them into fully deve ...

The Zip file generated in memory is experiencing corruption

I'm encountering an issue while attempting to serve a zip file generated in memory by Flask to a JavaScript front-end. However, the downloaded file appears corrupted and I am unsure of what mistake I may be making. @app.route('/route') def ...

My Discord.js bot was running smoothly until I added a new command, and suddenly everything went haywire. Can someone assist me in figuring out what went

I recently delved into the world of creating discord bots by following a simple tutorial and customizing it to suit my needs. Initially, the bot worked perfectly fine. However, when I attempted to add the "Mistake" command, it stopped functioning properl ...

Advantages of optimizing NodeJS/TypeScript application by bundling it with webpack

Currently, I am working on a Node/Express application and I am interested in incorporating the most recent technologies. This includes using TypeScript with node/Express along with webpack. I have a question: What advantages come with utilizing webpack t ...

Experiencing a RepositoryNotFoundError in TypeORM, although I am confident that the repositories are properly registered

I am creating a new application using Next.js + TypeORM and encountering an issue with the integration. RepositoryNotFoundError: No repository for "User" was found. It seems like this entity is not registered in the current "default" connection? Althoug ...

What is the best way to integrate JQuery URL in Joomla components?

Can anyone show me how to load a jquery URL in Joomla (Component)? I have a button that, when clicked, will reload the page and use the GET method to display a value from a variable. JavaScript: jQuery("#btnclickme").click(function(){ jQuery("#divpro").l ...

Filtering out specific properties from an element within a JavaScript forEach loop

const findBloodType = bloodCodeArray.find(bloodCode => bloodCode.code.toUpperCase() === bloodType.toUpperCase()).code; In my Angular code, I am trying to retrieve just the 'code' property of the 'bloodCode' element using a callback ...

Setting the borderRadius for a web view on Android Maps V3: A complete guide

In my application, I am using Android Map V3 and have encountered a bug specific to the Kit-Kat version. The chromium kit throws up an error message - nativeOnDraw failed; clearing to background color, which prevents the map from being displayed. Despite ...

What is the method for retrieving an image source using JavaScript?

I'm trying to retrieve the image source from my utils file and bind it to an img tag in my About.vue JS file, but I'm facing issues with the implementation. The first file is About.vue, and the second one is my utils file. <template> < ...