Utilizing jQuery to Refine an Array

I am currently working on implementing a feature to filter an array based on user input of a city. While I have successfully populated the drop-down menu, I am encountering an issue with the search bar functionality. The goal is to filter the array list according to what the user types in, but I am struggling to make the if statement work.

HTML :

<html>
  // HTML code  
   <body>

 <div class="jumbotron">


  <br>
  <button id="trigger-btn" class="btn">

  </button>
  <div id="container" class="hide">
      <input type="text" id="search" class="form-control"/>
      <br>
  </div>
</div>
  <span class="cities" id="cities"></span>
 </body>

   </html>

Javascript :

// Array of Cities in Colorado
var Cities_Colorado =  ["ACRES GREEN", "AGUILAR", "AIR FORCE ACADEMY", "AKRON", "ALAMOSA", "ALAMOSA EAST", "ALLENSPARK", "ALMA", "ANTONITO", "APPLEWOOD", "ARBOLES",
    "ARISTOCRAT RANCHETTES", "ARRIBA", "ARVADA", "ASPEN", "ASPEN PARK", "ATWOOD", "AULT", "AURORA", "AVON", "AVONDALE", "BASALT", "BATTLEMENT MESA", "BAYFIELD",
    "BENNETT", "BERKLEY", "BERTHOUD", "BETHUNE", "BEULAH VALLEY", "BLACK FOREST", "BLACK HAWK", "BLANCA", "BLUE RIVER", "BONANZA", "BOONE", "BOULDER", "BOW MAR",
    "BRANSON", "BRECKENRIDGE", "BRIGHTON", "BROOKSIDE", "BROOMFIELD", "BRUSH", "BUENA VISTA", "BURLINGTON", "BYERS", "CALHAN", "CAMPION", "CAMPO", "CANON CITY",
    "CARBONDALE"]

 // Filter List

  $(document).ready(function(){
    $('#trigger-btn').click(function(){
        $('#container').toggleClass('hide')
         })
        $.each(Cities_Colorado, function(key,value){
          (" "+key+ ": "+ value);
           $("#container").append("<span>" +"<li>"+value+ "</li>"+"</span>");

           $("#search").each(function(){

            $(value).text().indexOf();
           // Array Filtering 
           $(value).keyup(function(){
            var test=$(key).val()
            if ( indexOf( value ) === -1 ) {

            }else{ 
            }   
           })
          })
           })
          })  

Answer №1

If you're looking to filter a list based on user input, one approach is to refresh the list with each key press, testing each city against a regular expression.

$('.search').on('keyup', function() {
  let html = '', search = this.value;
  $.each(Cities_Colorado, function(index, city) {
    html += (new RegExp('^' + search, 'i')).test(city) ? `<li>${city}</li>` : '';
  });
  $('.cities').html(html);
}).trigger('keyup'); //initialize

Check out this JSFiddle for a demo.

I didn't directly copy your provided code as it seemed inactive, but I've included an illustrative example.

Here are some additional thoughts:

$.each() operates differently based on what you're iterating over.

$.each(array, function(index, value) {});
$.each(object, function(key, value) {});

Ensure <li> elements are contained within <ol> or <ul>.

Utilize template literals where suitable.

Dive into the world of regular expressions and the ternary operator.

If you're using jQuery UI, consider implementing jQuery Autocomplete for added functionality.

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 error message UnhandledPromiseRejectionWarning: TypeError: crypto.subtle.digest is throwing an error as it is

Encountering an error message saying "crypto.subtle.digest is not a function" when running unit tests using Jest for a function that utilizes crypto.subtle.digest(), have attempted to resolve the issue while using JSDOM with no success: 1. `[Utilizing J ...

What is the best way to update the amount input using Ajax?

I am looking to transfer the price selected from a drop-down list into an input field. I have the jQuery code in place to capture the selected value from the drop-down, but I understand that Ajax is needed for the next step. However, I'm unsure of how ...

React Native ScrollView with a custom footer that adjusts its size based on the content inside (

I've implemented the code below to ensure that the blue area in image 1 remains non-scrollable when there is sufficient space, but becomes scrollable when space is limited. However, I'm facing an issue where the ScrollView component is adding ext ...

The Highchart column chart is triggering the drilldown event multiple times

I have created a column chart using Highchart and I am facing an issue with the drilldown functionality. Whenever I click on a bar multiple times, the drilldown event triggers multiple times as well. This results in the drilldown event being triggered repe ...

Whenever I attempt to include state in a React class that is declared as a constant, I consistently encounter the error message: "TypeError:

Apologies for the redundancy, but as a newcomer to React, I previously inquired about a similar issue and have since modified my code. My current challenge involves trying to access a state value within a const React class. Below is the excerpt from my Ar ...

Error message: double AJAX call detected within an AJAX response

Currently, I am working on integrating a file with an API. The API initially sends some HTML and JavaScript to generate a search form, which is followed by processing the query from that search form. The issue arises when I attempt my second request, trig ...

Tips for creating a useState variable within the render() function in reactjs

I'm completely new to reactjs, and I've been trying to define useState variables within the render() method of a reactjs component. However, I keep running into an error: "Invalid hook call." class ProductDefinition extends Component { construc ...

Is there a way to drag an image into a designated area and automatically modify the container accordingly?

I am looking to implement a feature where users can drag an image into either container 1 or container 2. Depending on where the image is dropped, I want to update that specific container by making a database call or updating a row in one of my tables. My ...

Encountering an issue upon launching a new next.js project

Upon setting up my next.js project and running it, I encountered the following error: Error - ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[2].oneOf[8].use[1]!./node_modules/next/dist/build/webpack/loaders/postc ...

Having issues with my code. Attempting to interact with a specific element on a webpage using its ID, but encountering difficulties

Is there a way to automatically click on an element on a webpage based on its ID in the HTML code? The ID for this particular button is "input-optionXXX" where XXX represents a 3-digit number ranging from 100 to 400. I need a python script that can scan ...

Guide to Appending "Z" to a Date String Using Moment.js in JavaScript and Node.js

I am struggling to format my date to include the "Z" letter at the end. Despite numerous attempts, I have been unsuccessful. The desired format is "YYYY-MM-DDT00:00:00.000Z," but currently it does not include the Z How can I add the Z using moment? It&ap ...

Exploring the integration of functions from external JavaScript libraries into Angular factories and controllers

Is there a way to incorporate the functions from these libraries into my Angular factory? <head> <script type="text/javascript" src="js/3rdparty/strophe.js"></script> <script type="text/javascript" src="js/3rdparty/xml2json.js">< ...

Tips for utilizing jQuery buttons to submit forms in PHP

I'm struggling to submit the form using PHP from a button in jQuery. I've tried adding an ID for the button, but I can't seem to submit the values. Since I'm new to jQuery, this task is proving to be a bit challenging. Can anyone provid ...

Submitting information from a lone row within a table that is contained within a single form

Within my form, there is a table containing records generated by a for loop iterating through items in a list. Each record has a submit button that triggers an AJAX call to serialize and POST the form data to the controller. The goal is to only POST data f ...

Tips for accessing the value stored within the parent element

As someone who is new to the world of javascript and typescript, I am currently working on an ionic application that involves fetching a list of values from a database. These values are then stored in an array, which is used to dynamically create ion-items ...

What is the best way to paginate aggregated results in Mongoose?

In my project, I have a User model that is linked to two other associated models - Profile and WorkProfile. The Profile model contains basic information about the user like name, email, and home address, while the WorkProfile model stores details such as o ...

Preserve the button interface when it is clicked

Just diving into the world of CSS for the first time with a front end styling task, so apologies in advance for any errors or misunderstandings! I have a placeholder button that triggers a Modal (1): https://i.sstatic.net/1wT9Y.png When clicked, the but ...

Different approach to reach AngularJS isolated scope

Utilizing AngularJS isolated scope is an effective method for creating reusable components within angular directives. I find it to be quite beneficial. There are occasions when access to child scopes is necessary for data manipulation or method invocation. ...

Hovering over an element can trigger a dynamic swing animation effect

My objective is to animate an item to swing only when hovered over, utilizing CSS and jQuery, and of course, it should stop swinging when the mouse moves away. After browsing the web, I came across a code snippet that swings an element when the document i ...

Expression validation in AngularJS is a powerful tool for ensuring that

Attempting to implement input validation using an Angular expression because validation data will be sourced from the database. Attempting the following code: controller vm.key="ng-required" vm.value="true" html <input type="text" name="fi ...