How to insert error message in Input?

Asked

Viewed 484 times

0

I created a js to display the results as the search and the code works perfectly, as example below.

$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $(".blocos").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
    $('.linhas').remove();
  });
});
<script
  src="https://code.jquery.com/jquery-3.4.0.js"
  integrity="sha256-DYZMCC8HTC+QDr5QNaIcfR7VSPtcISykd+6eSmBW5qo="
  crossorigin="anonymous"></script>
<div class="busca"><input id="myInput" placeholder="Filtrar por nome" type="text" /></div>

<p class="blocos"> azul </p>
<p class="blocos"> verde </p>
<p class="blocos"> amarelo </p>

What I need is to display an error message when the user types a term that does not exist in the content inside blocks, if the user types see (it will soon display the green as it exists within the context) but if the user types "veg" it should return an error message). Does anyone know how I could do that?

1 answer

2


Add a content element to the error message (in the example, I used a span).

Add a counter before the filter, to store the number of successful occurrences in the search, if there is no occurrence this counter will contain the value 0. Then apply the toggle using the counter condition, if it is equal to zero is pq had no occurrence, then show the error message, otherwise hide the error message.

$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    var count = 0;
    $(".blocos").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
      count += $(this).text().toLowerCase().indexOf(value) > -1 ? 1 : 0;
    });
    $("span").toggle(count == 0);
    $('.linhas').remove();
  });
});
span{
 color: red;
 display: none;
}
<script
  src="https://code.jquery.com/jquery-3.4.0.js"
  integrity="sha256-DYZMCC8HTC+QDr5QNaIcfR7VSPtcISykd+6eSmBW5qo="
  crossorigin="anonymous"></script>
<div class="busca"><input id="myInput" placeholder="Filtrar por nome" type="text" /></div>

<p class="blocos"> azul </p>
<p class="blocos"> verde </p>
<p class="blocos"> amarelo </p>

<span>Não encontrado</span>

  • Thanks man, that’s right, fight!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.