Using a select dropdown to filter gender in Angular

I have a database where I need to filter by gender. The current setup is functioning properly.

However, when I try to filter by gender, both male and female are showing up because female includes the word "male". If I select female, then male disappears.

You can check my jsfiddle link here

<select name="" id="" ng-model="test.filterByGender">
<option value="">Filter By Gender</option>
  <option value="female">Female</option>
  <option value="male">Male</option>
</select>

Answer №1

Everything appears to be functioning correctly.

https://jsfiddle.net/jh59lpwq/18/

<tr ng-repeat="item in data.items | filter:data.filterByType | filter:(!!data.filterByCategory || undefined) && data.filterByCategory:true | filter:data.filterByPrice">
    <td>{{item.name}}</td>
    <td>{{item.category}}</td>
    <td>{{item.price}}</td>
 </tr>

By setting the comparator to true, it enforces a strict comparison of actual and expected values, distinguishing between 'male' and 'female'. However, it may not detect an empty value in the 'By category' field. To address this issue, you can specify that the filter should only be used if the value is present and defined.

I trust this information proves helpful.

Answer №2

Check out this AngularJS documentation

This function extracts a specific group of items from an array and presents them in a new array.

It functions similarly to the String.Contains method. For example, selecting "male" from a dropdown menu will display all data because the term "female" also contains the substring "male".

Answer №3

var app = angular.module("testApp", []);
app.controller('testCtrl', function($scope){
vm = this;
  
  vm.subjects = [
  
  {
            name : "Alpha",
            location:"TN",
            age : "25",
            gender:"female"
            },
            {
            name : "Beta",
            location:"TN",
            age : "44",
            gender:"male"
            },
            {
            name : "Gamma",
            location:"KE",
            age : "20",
            gender:"female"
            },
            {
            name : "Theta",
            location:"AN",
            age : "22",
            gender:"female"
            },
  
  
  ];
  
  angular.forEach( vm.subjects, function(subject){ 
  if(parseInt(subject.age) <= 25){
    subject.ageFilterCriteria = '<25'
    }
    else{
    subject.ageFilterCriteria = '>25'
    }
  
  })
  console.log(vm.subjects);
  vm.filterByAge = '';
  vm.filterByState='';
  vm.filterByGender='';
  
  vm.setFlag = function(value){
     if(value)
       vm.flag = true;
    else
       vm.flag = false;
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl as test">
<select name="" id="" ng-model="test.filterByState">
<option value="">Select a state</option>
  <option value="TN">TamilNadu</option>
  <option value="KE">Kerala</option>
  <option value="AN">Andra Pradesh</option>
</select>
<select name="" id="" ng-model="test.filterByGender" ng-change="test.setFlag(test.filterByGender)">
<option value="">By Gender</option>
  <option value="female">Female</option>
  <option value="male">Male</option>
</select>
<select name="" id="" ng-model="test.filterByAge">
<option value="">Select All</option>
  <option value="<25">Less Than 25</option>
  <option value=">25">Greater Than 25</option>
</select>
<table>
  <tr ng-repeat="subject in test.subjects |filter:{location:test.filterByState,ageFilterCriteria:test.filterByAge}| filter:{gender:test.filterByGender}:test.flag">
    <td>{{subject.name}}</td>
    <td>{{subject.gender}}</td>
    <td>{{subject.age}}</td>
  </tr>
</table>


</div>

give this a shot:

  <select name="" id="" ng-model="test.filterByGender" ng-change="test.flag =true">
   <option value="">By Gender</option>
   <option value="female">Female</option>
   <option value="male">Male</option>
  </select>


   <tr ng-repeat="subject in test.subjects |filter:{location:test.filterByState,ageFilterCriteria:test.filterByAge}|
                                            filter:{gender:test.filterByGender}:test.flag">

Answer №4

The Filter function is designed to display results based on matching items. This is why female rows appear when selecting male from the drop-down, as the word "female" contains the word "male".

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

The jQuery mouseout event is activated whenever my tooltip is hovered over

Recently, I encountered an issue with a menu that adds a https://i.sstatic.net/A0J2U.png Within the menu, there is jQuery code that functions to add a class on hover and remove it on mouse-out. The code snippet looks something like this... $(document).r ...

5 Creative Techniques for Manipulating Boolean Variables in If Statements

I am receiving a unique custom header value and the values I am getting are accurate. The expected values include: true, false, undefined. However, the response associated with the value: false is incorrect. Code Snippet let deviceStatus = req.headers[ ...

Struggling to make things function properly after the content changes following an ajax page load

Whenever the page loads, I execute this function to hide lengthy quoted posts by turning them into clickable links. This helps in preventing excessively long comments on my website: function hide_long_quotes() { $('.comments .comment_quote'). ...

``Look at that cool feature - a stationary header and footer that stay in place

I'm seeking advice on how to design a website with a fixed header and footer that remain consistent across all pages, with only the content area altering. I've come across a site as an example - , but couldn't figure out how it was done even ...

When navigating to a subsite or subfolder, the SVG href ID cannot be located

The topic at hand revolves around another issue: The challenge of creating an Ajax website with links from multiple subfolders. Take a look at the discussion where a solution for that problem was discovered. However, my current dilemma with that solution ...

String Replacement in JavaScript

Here's the scenario: I have a string var str="abc test test abc"; Is there a way to specifically replace the second occurrence of "abc" in the string using the str.replace() method? ...

Adjusting the scope value directly within a directive

I have a validation message that starts off hidden when the page loads due to the ng-show attribute. When the user clicks to delete an entry, the confirmation message for successful deletion appears by changing the ng-show value to false. Now, I need to h ...

Design a dynamic div element that gracefully transitions in and out from the edge of the screen

Currently, I am in the process of developing a simple clickdummy for an application layout. The layout includes a details view on the right side that should only be visible after clicking a button. I am struggling to figure out how to make this div move us ...

Executing gruntfile from the devDependencies module

Currently, I am testing out a .js framework. Within my package.JSON file, specifically inside devDependencies, I have the following: "devDependencies": { "myFramework": "https://github.com/myRepo/myFramework/tarball/master", "grunt": "~0.4.2", ...

Incorporating HTML content into a webpage element using ajax when clicked

When attempting to display an indicator while performing an ajax request, I was advised to have the indicator with an animated gif placed within the page element. Then, upon the successful completion of the ajax function, replace it with the desired data. ...

Ensure a minimum width is applied to a specific tooltip in Bootstrap that has a dynamically generated ID

I am working on an html view using Thymeleaf. The view contains a large table with various tooltips that have a style applied which is functioning correctly. However, I am now facing the challenge of adding a min-width specifically to the tooltips within a ...

The success function is not functioning properly with the validation engine

I'm having trouble getting this script to function properly as it keeps showing errors whenever I try to run it. $(document).ready(function() { $("#form1").validationEngine({ ajaxSubmit: true, ajaxSubmitFile: "note/note.php", ...

Why is the scrollHeight property of an element not updating when the display of its inner element is changed to 'none'?

For the sake of learning, I am attempting to develop a bootstrap-style navbar using angularJS 1.3.14. My approach involves creating directives for the navbar, navmenu, navMenuToggle, and navDropDown, with the navMenu serving as a container for toggle and d ...

Unable to load JavaScript file twice dynamically in Internet Explorer

I recently created this page where users can click on rows in a table to load data via an ajax request and dynamically generate a graph. While this functionality works smoothly in Chrome and Firefox, I'm experiencing issues with Internet Explorer 8. S ...

What is the best way to conceal a section of a div using CSS/React?

I am attempting to create a design where the entire content of a div is displayed initially, and then after clicking a button labeled "show less", only 300px of the content will be shown with the button changing to "show more". <div className="bod ...

React State Update Triggered by Changing Hidden Input/Textarea Value - No User Input Required

To activate a function when the contents of a hidden input, textarea, or textfield change in React without requiring user input to trigger it, you will need to dynamically adjust the value of the hidden input and then have the function automatically exec ...

Error: JSON parsing error - Unexpected token U found at the beginning of JSON string while making a POST request

When I make a post request to an API using the submit() function attached to an ng-click directive, sending data in JSON format, it returns an error. The request works fine on postman, so the error seems to be on the client side only. Additionally, the e ...

The padding of elements changes accordingly as the dimensions (width/height) of the header are adjusted

Currently, I'm tackling the challenges of working on my website and trying to understand JavaScript better. I am facing an issue where I want my aside menu's padding to adjust when my header shrinks in height. Furthermore, at the end of the web ...

What is the best way to send an object to its matching element?

Imagine having 4 labels and 4 buttons aligned next to each other. While it's common to update the label values by their corresponding button IDs, is there an alternative method using objects or references? <button onclick="myFunction()">Set dem ...

Angular: synchronously updating scope using data fetched asynchronously from a factory

What is the best way to accomplish this task? 1. factory.updater = function(varObjToBeUpdated){ $http.post('/url', {}) .success(function(data){ for (data_field in data) varObjToBeUpdated[data_field] = data[data_field ...