Ways to conceal a div element depending on the selection made in an AngularJS dropdown menu

Is there a way to dynamically hide a div based on a selected dropdown option? Here is the code snippet I have come up with:

<div>
   <p>Course Type</p>
   <div>
       <select name="student-type" id="student-type" class="icon-select-down" ng-model="studentType" ng-change="getOption(this)">
           <option value="java" selected>Java</option>
           <option value="angularjs">Angular js</option>
           <option value="reactJs">React js</option>
       </select> 
   </div>
</div>

<div ng-if="studentType">
   <p>Attendence Days</p>
   <div class="slice-item">
      <input type="text" class="input input-text" ng-model="attendenceDays" required validate-on="blur" ng-pattern="/^([1-9]|10)$/" invalid-message="'You must enter number between 1 to 25'" />
   </div>
</div>

In the controller, the following logic has been implemented:

$scope.getOption = function(value) {
    if (value.studentType == "angularjs") {
        $scope.studentType = "false";
    }
};

Any guidance on how to solve this issue would be greatly appreciated.

Answer №1

What's the problem with your code?

The issue lies in the logical aspect. The condition ng-if="studentType" is used to display the input container, but within the change event,

if (value.studentType = "angularjs")
is utilized. This does not check a condition; rather, it performs an assignment operation. It should be written as
if (value.studentType == "angularjs")
or
if (value.studentType === "angularjs")
to compare the value of value.studentType with the string "angularjs". In the current setup, the if statement will always assign "angularjs" to studentType, followed by assigning "false" to studentType inside the if block. This process is unnecessary.

There are multiple ways to resolve this issue. I recommend two options:

  • Option 1: Check the value of studentType inside the template. Display the input only if studentType is not equal to "angularjs". Simply add the condition
    ng-if="studentType !== 'angularjs'"
    in the template without any additional controller logic.

Working Demo

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
    // $scope.showInput = true;
    // $scope.getOption = function (value) {
    //     if (value.studentType == "angularjs") {
    //         $scope.showInput = false;
    //     }
    // };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
    <div>
        <p>Course Type</p>
        <div>
            <select name="student-type" id="student-type" class="icon-select-down" ng-model="studentType"
                ng-change="getOption(this)">
                <option value="java" selected>Java</option>
                <option value="angularjs">Angular js</option>
                <option value="reactJs">React js</option>
            </select>
        </div>
    </div>

    <div ng-if="studentType !== 'angularjs'">
        <p>Attendance Days</p>
        <div class="slice-item">
            <input type="text" class="input input-text" ng-model="attendanceDays" required validate-on="blur"
                ng-pattern="/^([1-9]|10)$/" invalid-message="'You must enter a number between 1 and 25'" />
        </div>
    </div>
</div>

  • Option 2: Within the change function, evaluate the selected option's value and set a visibility boolean accordingly. Adjust the input's visibility based on that boolean.

Working Demo

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
    $scope.showInput = true;
    $scope.getOption = function (value) {
        $scope.showInput = value.studentType !== "angularjs";
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
    <div>
        <p>Course Type</p>
        <div>
            <select name="student-type" id="student-type" class="icon-select-down" ng-model="studentType"
                ng-change="getOption(this)">
                <option value="java" selected>Java</option>
                <option value="angularjs">Angular js</option>
                <option value="reactJs">React js</option>
            </select>
        </div>
    </div>

    <div ng-if="showInput">
        <p>Attendance Days</p>
        <div class="slice-item">
            <input type="text" class="input input-text" ng-model="attendanceDays" required validate-on="blur"
                ng-pattern="/^([1-9]|10)$/" invalid-message="'You must enter a number between 1 and 25'" />
        </div>
    </div>
</div>

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

Passing a variable through an ajax request upon successful completion

Is there a way I can include the variable 'schedule_id[i]' in the result of this call? Can I also add this variable to the data object? Here's my code: for (var i = 0; i < schedule_id.length; i++) { //Making an AJAX request $.a ...

Having trouble getting NPM environment variables to function properly on a Windows system?

I have a confusion in my package.json file where I am attempting to compile less code using versioning. Here is an example of what I am trying to achieve: "scripts" { ... "build:css": "lessc --source-map css/index.less build/$npm_package_name.$npm_package ...

Disregard earlier callback outcome if there has been a change in the state since then

I am facing an issue with my page that displays a list of countries retrieved from an external library. When I click on a country, it should show me all the cities in that specific country. Each country object has a provided method to fetch the list of c ...

React component causing function to fire twice on click

Summary: My toggle function is triggering twice upon clicking the button. Within a React component (using Next.js), I am utilizing the useEffect hook to target the :root <html> element in order to toggle a class. The script is as follows: useEffect( ...

Discovering the optimum route within a 2D array given specific limitations using Dynamic Programming

Hey, I have a query related to dynamic programming (dp) that goes like this: Input: A 2D array of numbers Output: The maximum sum of a path from (0,0) to (n-1,n-1) with the following conditions: You can only move down and right i.e. from (A[i-1][j]) t ...

Issue with displaying record attribute as a text variable

I'm currently attempting to retrieve the attribute odata.type from a record so that I can adjust my EditForm based on its value. Strangely, when I utilize a constant to achieve this and print it with console.log, it appears as follows: ƒ HWType(_ref ...

Retrieve the JavaScript object that was initialized within a function

As I venture into the world of working with javascript objects and php objects, I've encountered an issue. While everything seems to be functioning correctly so far, I'm having trouble accessing the javascript object created in the ajax success r ...

Dilemma of interdependencies between Socket.io and requirejs

I am facing a challenge with my legacy express project that has two servers. The project includes two separate client files: requirejs.config({ baseUrl: '/js' , paths: { "jquery": "lib/jquery/jquery-2.1.1.min", "socket.io" : "lib/socket/ ...

The last javascript file that was included has been overlooked

When using jqplot, I noticed that the last included plugin is being ignored. If I switch their positions, the first to last one works while the last one does not. There are no errors in the console to indicate what might be going wrong. Moving the canvasOv ...

Steps to verify if a value is an integer:

Lately, I've been working on a "spinner" that increments and decrements a number by 1 each time. However, I'm struggling to add validation to the program so that it only accepts integers (no decimals). I've tried looking into NaN and parseVa ...

Tips for displaying an object's key/value pairs on a webpage

I'm attempting to use jQuery's .each() function to write the key/value pairs from an object onto the page. However, I am only able to get it to display the last key/value pair. If you want to check out a code example and demo, here is the link: ...

Leveraging AngularJS to fetch data from two distinct JSON files

I am faced with the challenge of incorporating 2 JSON file examples into my project. The format of each file is different, so I am exploring the best approach using an angular controller to handle them effectively. These JSON files are not being fetched fr ...

Uh-oh! The module "side-channel" cannot be found. An error occurred in the loader with code 936 when trying to run the command "npm start"

During the execution of npm start to view my React app, I encountered the following error: > react-scripts start node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot find module 'side-channel' Require stack: - C:\Users&bs ...

The functionality of the jQuery addClass method is failing to work when implemented on

Hello, I'm currently attempting to implement a CSS Style on an <img> tag that does not have any assigned class or id. Below is my code snippet: ===CSS=== .tgll-navi { //custom class for navigation bar .navi-left { //.navi-left float:right; ...

Combining an Angular factory with another factory

I'm facing some difficulties with injecting one factory into another. The error message I'm getting is: `ReferenceError: testDataService is not defined` I thought it would be a simple issue to resolve, but it's turning out to be quite c ...

The class field remains unset

I'm currently developing my own custom CQRS library and I've encountered an issue where a specific field is not being set correctly. The problem appears to be within classes that extend my AggregateRoot abstract class. Take a look at the followin ...

Running of code in <script> tag

At what point does the code inside script tags start executing? Does it happen in order? <html> <head> <title>Canvas tutorial</title> <script type="text/javascript"> function draw(){ var canvas = document.getElementById ...

Exploring the Power of Map with Angular 6 HttpClient

My goal is to enhance my learning by fetching data from a mock JSON API and adding "hey" to all titles before returning an Observable. Currently, I am able to display the data without any issues if I don't use the Map operator. However, when I do use ...

Updating values in mongoDB using Express.js and axios: A step-by-step guide

I need help figuring out how to update a specific post's data in my mongoDB using its object id. I have created an HTML form that displays the selected post's data and allows me to make changes, then submit the updated data to http://localhost:50 ...

Interactions between JavaScript and PHP scripts within a web application

THE SCENARIO In the midst of creating a web application that dynamically loads content by fetching data from a MongoDB database where items and their respective authors are stored in separate collections within the same database. The author's ID is s ...