Steps for utilizing the Bootstrap filter to search for a specific name starting with a particular letter

I have implemented a bootstrap filter for searching, but I am encountering an issue. Currently, when I type 'n', it displays all names containing 'n' like Nathan and Arjan. However, I would like it to only show names that start with 'n', such as Nathaan and Narima. Here is the blade.php code snippet:

<input class="form-control" id="myInput" type="text" placeholder="Search..">
<tbody id="myTable">
  <tr>
    <td>John</td>
  </tr>
  <tr>
    <td>Anja</td>
  </tr>  
</tbody>

Here is my script portion:

<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>

Answer №1

A handy function known as startsWith is available for you to utilize. For more detailed information, please refer to the documentation provided at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith

<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().startsWith(value))
    });
  });
});
</script>

Answer №2

If you feel like it, go ahead and modify the method.

$("#myInput").on("input", function() {
    var userInput = $(this).val().toLowerCase();
    var items = $("tr td");

    // Start by hiding all items:
    items.parent().hide();

    // Show only items that match user input:
    items.filter(function () {
        return $(this).text().toLowerCase().indexOf(userInput) == 0;
    }).parent().show();
});

Answer №3

One alternative method is to utilize the power of Regular Expressions (RegExp):

$(document).ready(function() {
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      /* $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) */
      const searchRegEx = new RegExp(`^${value}`, 'i');
      $(this).toggle(searchRegEx.test($(this).text().trim()));
    });
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

<input class="form-control" id="myInput" type="text" placeholder="Search..">
<table class="table table-bordered">

  <tbody id="myTable">
    <tr>
      <td>John</td>
    </tr>
    <tr>
      <td>Anja</td>
    </tr>
  </tbody>
</table>

Answer №4

When using .charAt(0), the result set is filtered to match the first character. This example is based on a modification of a basic code snippet from w3schools.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myTable {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #ddd;
  font-size: 18px;
}

#myTable th, #myTable td {
  text-align: left;
  padding: 12px;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
  background-color: #f1f1f1;
}
</style>
</head>
<body>

<h2>My Customers</h2>

<input type="text" id="myInput" onkeyup="filterBy()" placeholder="Search..." title="Type in a name">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Berglunds snabbkop</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Koniglich Essen</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Italy</td>
  </tr>  
  <tr>
    <td>Marimba</td>
    <td>Something</td>
  </tr>
    <tr>
    <td>Marimba</td>
    <td>Something</td>
  </tr>
  <tr>
    <td>North/South</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Paris specialites</td>
    <td>France</td>
  </tr>
</table>

<script>
function filterBy() {
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      if (txtValue.toUpperCase().charAt(0) ==  filter.charAt(0)) {
          tr[i].style.display = "";
        }
      } else {
        tr[i].style.display = "none";
      }
      if(filter.length == 0)
      {
          tr[i].style.display = "";
      }
    }       
  }
}
</script>

</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

When CSS animations are active, the jQuery hide().slideDown() function fails to execute properly

I am a beginner in this field. Initially, I used jQuery to create three divs (buttons) that slid down when the page loaded. I also added an expansion effect on mouseover. This method worked fine in Safari but not in Firefox. So I made some modifications. ...

Angular JS - Implementing a flexible URL structure for fetching data using $http GET

I have been working on implementing a login feature for my app by using a custom REST API. Initially, I was able to successfully authenticate by manually entering the complete URL with the username and password: http://www.myexample.com/ACTION/USER/PASSWO ...

Using Cucumber for testing javascript-loaded content can be incredibly powerful and effective in ensuring the functionality

As I develop my Rails application, I've decided to incorporate a combination of Test Driven Development and Behavioral Driven Development into my process. The challenge arises as my app utilizes the MochaUI web application user interface framework, w ...

JavaScript Challenge: Calculate the Number of Visible Characters in a Div

I have a div with text content (a string of length S) that is fixed in size but can be of any length. When the text exceeds a certain point (referred to as L), it gets truncated, and the portion beyond that limit becomes invisible. In other words, characte ...

Programmatically setting properties for elements

I have a question about how to programmatically add a prop to a component in my React project. Here is the scenario: In the render() method, I have the following code snippet: <TextField name="password" va ...

Issues with loading SourceMap in DevTools after upgrading from Bootstrap 3 to 4

I am currently working on a project with Angular 6 and .NET MVC where I am in the process of upgrading from Bootstrap 3 to Bootstrap 4. Initially, I had been using the Bootstrap 3 CDN and everything was working smoothly. However, I recently had to switch t ...

Ways to make a chosen row stand out in an *ngFor loop?

Struggling to find a solution within Angular2 for setting a css class when selecting a row. I want to achieve this without relying on jQuery. <table class="table table-bordered table-condensed table-hover"> <thead> <tr> ...

Determine the dropdown list value by analyzing the final two variables in a textfield

In my textfield, car registration numbers are meant to be entered. These registrations are based on years in the format GT 74454 12, with the last two digits "12" representing the year 2012. I am looking for a script that can automatically detect the last ...

jinja2.exceptions.UndefinedError: The variable 'participant' has not been defined

I am currently in the process of developing a video chat web application using Twilio, and I have been following a tutorial on how to build the application: . However, I keep encountering an error mentioned in the title. It seems like I am trying to access ...

Struggling with integrating vue pagination

I am looking to add pagination functionality to my website and stumbled upon a visually appealing example that is compatible with Vue. However, despite my lack of experience with Vue, I am struggling to get the demo to work properly. The pagination compon ...

What is the best method to assign each key in an Object to the corresponding value in another Object?

Suppose I have an object called data: { first: 'Zaaac', last: 'Ezzell', title: 'Mrs', mail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83ece6f9f9e6efefb3c3f1e6e7e7eaf7ade ...

retrieve a static method that returns an asynchronous value

Is there a way to have a static ES6 method in my code that simply returns a value instead of a promise? I'm looking for a solution to this problem: export default class Member { static existingMember() { var _existingMember; // DB.findExist ...

Executing various axios requests to retrieve diverse data and populating multiple sections of the user interface in React Native

I am struggling to display various categories of movies on the same screen, such as "POPULAR MOVIES", "RECOMMENDED MOVIES", and "NEWEST MOVIES". I have been able to retrieve data for the "POPULAR MOVIES" section using an API call, but I'm unsure of th ...

Is there a way to verify the status of a radio button without using a submit button?

What's the best way to determine if the radio box value is Pearson or euclidean? Here's what I have so far: if ($_SERVER['REQUEST_METHOD'] === 'POST') { if($_POST['radio'] == 'Euclidean'){ ...

Output PHP code within the HTML content using javascript's innerHTML functionality

I wrote a PHP function that increments by +1 every time it is executed. function count_likes(){ $collect=file_get_contents('like_counter.txt')+1; $count=file_put_contents("like_counter.txt", $collect); echo $collect; I also have a JavaScr ...

Utilizing arrow keys as a means of setting focus (HTML & JavaScript)

Is it possible to program the left arrow key to function like the tab button (moving focus to the next focusable item) and the right arrow key to function as a shift+tab (moving focus to the previous focusable item)? I've made some progress with the ...

Dynamic routes in NextJS automatically append a .txt extension to the end of the URL

Issue: When using NextJS, the link <Link href="/link">link</Link> redirects to /link.txt For a simple link like this, HTML <a href="/link">link</a> can be used instead The real problem arises when using NextJS ...

Maintain the values of radio buttons, dropdowns, and checkboxes using Javascript

When I click on a radio button, it activates a drop down menu. Upon selecting different values from the drop down, various checkboxes become visible. Now, I want to preserve the selection of the radio button along with the selected drop down values and ch ...

Are your macOS devices not displaying the Scrollbar CSS buttons correctly?

I need help troubleshooting why my buttons are not appearing in the scrollbar on macOS. They function properly on Windows, so I suspect there may be a typo or error in my code. Can anyone take a look and provide some insight? ::-webkit-scrollbar { wid ...

JavaScript for Designing in Two and Three Dimensions

I need to take a 2D design created in microstation and display it on the web using a tool like javascript, Unity 3D, or another similar option. The web tool should have basic functionality like reshaping or adding new shapes. My current approach involves c ...