What is the best way to dynamically filter checkboxes based on user input using jQuery in the following code snippet?

In order to filter the checkboxes in the code below, I would like to only display the checkbox with a value matching the input entered in the input field with the class "js-filter-input". For example, if I type "uni1" in the input field, I want to show only the checkbox with the value of "uni1" and hide all other checkboxes. However, my current code is not functioning correctly.

$( document ).on( 'keyup', '.js-filter-input', function () { 
    var val;
    var $content = $( this ).parent().next().find( ".search-filter-con" ).find( '.label-name' ).text() + " ";
    if ( val = $( this ).val() ) {
        
        $( '.group-checkbox .label-name', $content ).each( function () {
            var patt = new RegExp( val, 'i' );
            if ( patt.test( $( this ).data( 'en' ) ) || patt.test( $( this ).data( 'fa' ) ) || patt.test( $( this ).data( 'search' ) ) ) {
                $( this ).parent().show();
            } else {
                $( this ).parent().hide();
            }
        });
    } else {
       $( '.group-checkbox', $content ).show();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="search-container2">
  <input class="search_box js-filter-input" placeholder="" name="" type="text">
  <button value="" class="search_submit" name="search_submit" type="submit"><i class="fa fa-search"></i></button>
</div>
<div class="searchList">
  <div class="sampleContainer mCustomScrollbar _mCS_3 mCS-dir-rtl mCS_no_scrollbar">
    <div class="mCustomScrollBox mCS-light-thin mCSB_vertical mCSB_inside">
      <div class="mCSB_container mCS_y_hidden mCS_no_scrollbar_y" dir="rtl">
        <div class="search-filter-con">
          <div class="group-checkbox">
            <div class="squaredFour">
              <input type="checkbox" value="None" id="uni1" name="check" />
              <label for="uni1"></label>
            </div>
            <label class="label-name" for="uni1" data-fa="uni1" data-en="uni1" data-search="uni1>uni1</label>
          </div>
          <div class="group-checkbox">
            <div class="squaredFour">
              <input type="checkbox" value="None" id="uni2" name="check" />
              <label for="uni2"></label>
            </div>
            <label class="label-name" for="uni2" data-fa="uni2" data-en="uni2" data-search="uni2">uni2</label>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Answer №1

When examining your example, the .search-filter-con element contains two label-name elements instead of just one. Therefore, the provided code will retrieve both of them.

$(this).parent().next().find(".search-filter-con").find('.label-name').text()

If you want to extract separate text values, you should utilize the .each() function to iterate through the labels:

$(this).parent().next().find(".search-filter-con").find('.label-name').each(function(){
   console.log($(this).text() + ',');
});

It is unclear why you are using $(this).parent().next(). Unless there are multiple inputs and divs with identical classes that need to be referenced individually.

To implement filtering using input, you can employ .filter() in conjunction with indexOf():

$(document).on('input', '.js-filter-input', function() {
  var val = $(this).val().trim();
  if (val !== '') {
    $(this).parent().next().find(".group-checkbox").hide().find('.label-name').filter(function(){
      var FaData = $(this).data('fa');
      var EnData = $(this).data('en');
      return FaData.indexOf(val) > -1 || EnData.indexOf(val) > -1; 
    }).closest('.group-checkbox').show();
  }else{
    $('.group-checkbox').show();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="search-container2">
  <input class="search_box js-filter-input" placeholder="" name="" type="text">
  <button value="" class="search_submit" name="search_submit" type="submit"><i class="fa fa-search"></i></button>
</div>
<div class="searchList">
  <div class="sampleContainer mCustomScrollbar _mCS_3 mCS-dir-rtl mCS_no_scrollbar">
    <div class="mCustomScrollBox mCS-light-thin mCSB_vertical mCSB_inside">
      <div class="mCSB_container mCS_y_hidden mCS_no_scrollbar_y" dir="rtl">
        <div class="search-filter-con">
          <div class="group-checkbox">
            <div class="squaredFour">
              <input type="checkbox" value="None" id="uni1" name="check" />
              <label for="uni1"></label>
            </div>
            <label class="label-name" for="uni1" data-fa="امير كبير" data-en="امير كبير" data-search="uni1">امير كبير</label>
          </div>
          <div class="group-checkbox">
            <div class="squaredFour">
              <input type="checkbox" value="None" id="uni2" name="check" />
              <label for="uni2"></label>
            </div>
            <label class="label-name" for="uni2" data-fa="تهران" data-en="تهران" data-search="uni2">تهران</label>
          </div>
        </div>
      </div>
    </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

Understanding intricate JSON structures with JavaScript

Here is the JSON structure that I am working with: var data = [ { "country":"Andorra", "code":"AD", "state":[ { "state_code":"AD1", "state_description":"aaAndorra1" }, { " ...

Using jQuery and HTML to create numerous links that direct to a solitary iframe

I created a basic overlay setup using css, html, and jQuery. Here's how it looks: <a class="activator" id="activator" style="" href="#">hello</a> <div class="overlay" id="overlay" style="display:none;"></div> <div style="d ...

Is your AngularJS code throwing an error?

$scope.logout = function () { //var auth_token = $cookieStore.get('auth_token'); Auth.delete({ 'auth_token': $cookieStore.get('auth_token') }, function(data){ $scope.isLoggedIn = false; $cookieSto ...

Unable to locate the Chart object within the chartjs-plugin-labels.js file

Hello there, I am currently working on an Angular project where I want to incorporate a chart plugin. To achieve this, I executed the following commands: npm install angular2-chartjs npm install chartjs-plugin-labels Following that, I imported it into my ...

The map displayed on google.com appears different from the one featured on our website

The integration of the JS for the Google map on our website is working smoothly without any issues. However, when I zoom into our address on google.com/maps, our Hotel is listed as "Hotel". On the map displayed on our website, there are only a few entries ...

Exploring and extracting values from nested arrays of objects in JavaScript and React

Hey there, I am having trouble getting the data from the backend server to display on a chart library. Can you please take a look at my code and help me out? const data = [ { id: "americano", data: [{x: "10",y: 10,}, {x: &quo ...

Proceed to the following stage by clicking on an element in introJS

I'm currently developing a new application with angularjs and incorporating intro.js for a guided product tour. My goal is to allow the user to click on a specific element, causing intro.js to zoom in on that precise element instead of following the ...

Instructions for importing a JSON 3D model and placing it at the center in Three.js

Is there a way to accurately load a JSON object and position it at the origin? I have tried using object.position.x and mesh.position.x but haven't been successful in aligning the object with the origin. My goal is to calculate the maximum and minimum ...

Exploring the source code of NPM public and private packages within the node_modules directory

As someone who is new to javascript development, I want to create a private npm package that cannot be accessed by users. However, I have noticed that I can still view the code of other npm packages labeled as closed-source by entering their node_modules s ...

Included adaptable background-images in the upload

Recently, I developed a RoR based app/website that allows clients to upload their own background image to the cover page. Although the current setup works well with a single image, I am aiming to enhance the site's responsiveness by enabling clients t ...

Providing both app and io as parameters to a module

Extracted from my server.js: const app = require('express')(); const server = require('http').createServer(app); const io = require("socket.io").listen(server); server.listen(port, function(){ console.log('Server listening at ...

Leveraging jQuery plugins within an AngularJs application

I am currently trying to implement the tinyColorPicker plugin from here in my Angular app, but I am facing difficulties with it. An error message keeps appearing: TypeError: element.colorPicker is not a function In my index.html file, I have included th ...

Using Regular Expressions in an ExpressJS Router

When working with ExpressJS, is there a way to combine the following routes into one using RegEx? app.get(/^\/blog(?:\/p(\/\d+)?)?$/, blog.list); ...

A single integer variable that is shared across all sessions in node.js

Is there a way to create an integer variable that is shared among all client sessions in node.js and can be accessed in client HTML? I need this variable to be displayed in the HTML page and have the ability to update it within the page, with the new val ...

detecting a click event outside of a specific element using jQuery

var onEnableHelpCheckChange = function() { // Checking if checkbox is checked if ($("#enable-help").prop('checked') === true) { $('#nav-help-img').attr('src','/assets/images/help-1.png') ...

dropdown menu center

I'm currently working with a Bootstrap drop-down menu and I'm trying to figure out how to center the menu directly over the button. Currently, it's aligning to the left or right of the button depending on available space. Any help would be a ...

PHP and jQuery creating a three-tiered drop-down navigation menu

My task involves creating a jQuery dropdown menu using PHP-generated HTML from a database table of categories: cats (db table) <ul class="dropdown"> <?php $sql ='SELECT * FROM cats WHERE cat_parent = 0'; $result = $db->s ...

Avoid reloading the page when the form is submitted using form.trigger('submit') command

My current code functions properly when the user clicks on the form's submit button: // load dashboards when filter form is submitted $('div.active form.filter-form').submit(function (e) { // get subm ...

In an empty JavaScript MVVM Organization View, the ViewModel is packed with lines of code

I find myself always placing all of my code within the ViewModel because nothing else seems to fit. What kinds of things should be included in the view? Does anyone have any examples? ...

How can I verify the submitHandler function using the JavaScript id?

Is there a way to implement a submitHandler on an id for validation purposes? I would like to specify a specific id to handle the validation. Here is an example of the current code: $("#validate").validate({ rules: { "name-contact": { ...