user search

6

1.- For the search based on the content of the divs, is that a good practice?

2.- When I perform a search, and then I delete all of the input, how do I return to its initial state, that is to say that all the users are shown, are there events that help me solve the problem?

    $(function(){
       var data = [];
      $('#usuarios').children('li').each(function () {
        data.push($(this).children('div').text());
         });
     
      function igualar(buscados) {
        var palabras = [];
      
        $.each(buscados, function(idx, buscado) {
          palabras.push(buscado.toLowerCase());
        });
      return palabras;
      }
      
      function orden(a, b) {
        if (a.normal > b.normal) {
          return 1;
        }
        if (a.normal < b.normal) {
          return -1;
        }
        return 0;
      }
      
     function existe(elem, lista){
        for(var i=0;i<lista.length; i++){
          if(lista[i]==elem){
            return true;
          }
        }
        return false;
      }
      
      function eliminarDivs(posibles){
          
          $('#usuarios').children('li').each(function () {
          if(!existe($(this).children('div').text(),posibles)){
            var ide= $(this).children('div').attr('id');
          document.getElementById(ide).parentNode.remove();
          } 
          });
      }

      data = igualar(data);
     
      data.sort(orden);
      
      $("#nombre").on("input",function() {
        var key = document.getElementById("nombre").value,
            posibles = [],
            lucky = false;

        key =key.toLowerCase();

        $.each(data, function(idx, word) {

          if (word.indexOf(key) !== -1) {
            posibles.push(word);
            
            if (key === word) {
              lucky = word;
            }

          }
        });
        eliminarDivs(posibles);
      });
    })
#usuarios li{
display:inline-block;
}
li{
width:30%;
height:100px;
text-align:center;
}
li:hover{
background:#b6b5e7;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    Escribe para buscar usuarios:
    <input type="text" id="nombre">

<ul id="usuarios">
  <li><div id="1">miesha</div></li>
  <li><div id="2">ronda</div></li>
  <li><div id="3">thor</div></li>
  <li><div id="4">superman</div></li>
  <li><div id="5">batman</div></li>
  <li><div id="6">susan</div></li>
  <li><div id="7">minerva</div></li>
  <li><div id="8">pedro</div></li>
  <li><div id="9">diana</div></li>
  <li><div id="10">fedor</div></li>
</ul>
    
asked by hubman 14.02.2017 в 16:46
source

3 answers

10
  • There is no greater inconvenience with using the content of the DIV to create your array of values. I would add the trim () function at the end to remove any space at the beginning and end.

  • If you are going to reuse the displayed values, I recommend that you do not remove the elements, but hide them using the jQuery hide () and show () function.

  •     $(function(){
           var data = [];
          $('#usuarios').children('li').each(function () {
            data.push($(this).children('div').text());
             });
         
          function igualar(buscados) {
            var palabras = [];
          
            $.each(buscados, function(idx, buscado) {
              palabras.push(buscado.toLowerCase());
            });
          return palabras;
          }
          
          function orden(a, b) {
            if (a.normal > b.normal) {
              return 1;
            }
            if (a.normal < b.normal) {
              return -1;
            }
            return 0;
          }
          
         function existe(elem, lista){
            for(var i=0;i<lista.length; i++){
              if(lista[i]==elem){
                return true;
              }
            }
            return false;
          }
          
          function eliminarDivs(posibles){
              
              $('#usuarios').children('li').each(function () {
              if(!existe($(this).children('div').text(),posibles)){
                $(this).hide();
              } 
              else $(this).show();
              });
          }
    
          data = igualar(data);
         
          data.sort(orden);
          
          $("#nombre").on("input",function() {
            var key = document.getElementById("nombre").value,
                posibles = [],
                lucky = false;
    
            key =key.toLowerCase();
    
            $.each(data, function(idx, word) {
    
              if (word.indexOf(key) !== -1) {
                posibles.push(word);
                
                if (key === word) {
                  lucky = word;
                }
    
              }
            });
            eliminarDivs(posibles);
          });
        })
    #usuarios li{
    display:inline-block;
    }
    li{
    width:30%;
    height:100px;
    text-align:center;
    }
    li:hover{
    background:#b6b5e7;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        Escribe para buscar usuarios:
        <input type="text" id="nombre">
    
    <ul id="usuarios">
      <li><div id="1">miesha</div></li>
      <li><div id="2">ronda</div></li>
      <li><div id="3">thor</div></li>
      <li><div id="4">superman</div></li>
      <li><div id="5">batman</div></li>
      <li><div id="6">susan</div></li>
      <li><div id="7">minerva</div></li>
      <li><div id="8">pedro</div></li>
      <li><div id="9">diana</div></li>
      <li><div id="10">fedor</div></li>
    </ul>
        
    answered by 14.02.2017 / 16:56
    source
    5

    I hope it serves you,

    $(function(){
           var data = [];
          $('#usuarios').children('li').each(function () {
            data.push($(this).children('div').text());
             });
         
          function igualar(buscados) {
            var palabras = [];
          
            $.each(buscados, function(idx, buscado) {
              palabras.push(buscado.toLowerCase());
            });
          return palabras;
          }
          
          function orden(a, b) {
            if (a.normal > b.normal) {
              return 1;
            }
            if (a.normal < b.normal) {
              return -1;
            }
            return 0;
          }
          
          
          
          
         function existe(elem, lista){
            for(var i=0;i<lista.length; i++){
              if(lista[i]==elem){
                return true;
              }
            }
            return false;
          }
          
          function eliminarDivs(posibles){
              $('#usuarios').children('li').removeClass('invisible')
              $('#usuarios').children('li').each(function () {
                   if(!existe($(this).children('div').text(),posibles)){
                var ide= $(this).children('div').attr('id');
                $('#'+ide).parent().hide()
              } else {
                var ide= $(this).children('div').attr('id');
                $('#'+ide).parent().show()
              }
              });
          }
    
          data = igualar(data);
         
          data.sort(orden);
          
          $("#nombre").on("input",function() {
            var key = document.getElementById("nombre").value,
                posibles = [],
                lucky = false;
    
            key =key.toLowerCase();
    
            $.each(data, function(idx, word) {
    
              if (word.indexOf(key) !== -1) {
                posibles.push(word);
                
                if (key === word) {
                  lucky = word;
                }
    
              }
            });
            eliminarDivs(posibles);
          });
        })
    #usuarios li{
    display:inline-block;
    }
    li{
    width:30%;
    height:100px;
    text-align:center;
    }
    li:hover{
    background:#b6b5e7;
    }
    .invisible {
      visibility:hidden;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        buscar usuario:
        <input type="text" id="nombre">
    
    <ul id="usuarios">
      <li><div id="1">miesha</div></li>
      <li><div id="2">ronda</div></li>
      <li><div id="3">thor</div></li>
      <li><div id="4">superman</div></li>
      <li><div id="5">batman</div></li>
      <li><div id="6">susan</div></li>
      <li><div id="7">minerva</div></li>
      <li><div id="8">pedro</div></li>
      <li><div id="9">diana</div></li>
      <li><div id="10">fedor</div></li>
    </ul>
        
    answered by 14.02.2017 в 17:00
    1

    I do not know how to handle many of your parts but I have something different that could help you.

    First, make the query with which the list of users and the information on the page will be made.

    @Filtro VARCHAR(100),
    @Pagina INT ,
    @RegistrosPorPagina INT
    AS
    BEGIN
      SET NOCOUNT ON;
      WITH Usuarios
      AS(
            SELECT ROW_NUMBER() OVER(IdUsuario) AS RowNumber              
              ,Idem.Nombre
            FROM UsuariosTabla            
            WHERE   
             (
                    (Nombre LIKE  '%' + ISNULL(@Filtro, '') + '%' )
                    OR (IdUsuario LIKE  '%' + ISNULL(@Filtro, '') + '%' )
            )
    
      )
      SELECT (SELECT COUNT (IdUsuario) FROM Usuarios) AS TotalRegistros ,
                * FROM Usuarios
      WHERE RowNumber BETWEEN ( @Pagina - 1 ) * @RegistrosPorPagina + 1
                      AND     ( @Pagina * @RegistrosPorPagina )
    
    END
    

    Then in your data layer, use a list model for users and a page object model

    public IEnumerable<ModUsuario> GetInbox(ModInbox objBusqueda,ref ClsModPaginacion objModPaginacion, out ClsModErrorBase objModErrorBase)
        {
            List< ModUsuario>  lstUsuarios = new List<ModUsuario>();
            objModErrorBase = new ClsModErrorBase();
            SqlDataReader sqlDataReader = null;
            try
            {
                ICollection<SqlParameter> lstSqlParameter = new List<SqlParameter>();
                lstSqlParameter.Add(new SqlParameter("@Filtro", SqlDbType.VarChar) { Value = string.IsNullOrEmpty(objBusqueda.Filtro) ? string.Empty : objBusqueda.Filtro });
                lstSqlParameter.Add(new SqlParameter("@Pagina", SqlDbType.Int) { Value = objModPaginacion.Pagina });
                lstSqlParameter.Add(new SqlParameter("@RegistrosPorPagina", SqlDbType.Int) { Value = objModPaginacion.RegistrosPorPagina });
                sqlDataReader = SqlHelper.ExecuteReader(this.strConexion, CommandType.StoredProcedure, "_492.spdOpinGetLstUsuario", lstSqlParameter.ToArray());
                if (sqlDataReader != null)
                {
                    if (sqlDataReader.HasRows)
                    {
                        while (sqlDataReader.Read())
                        {
                            if (objModPaginacion.TotalRegistros == 0)
                            {
                                objModPaginacion.Asignar(decimal.Parse(sqlDataReader["TotalRegistros"].ToString()));
                            }
                            var objUsuario = new ClsModOpinEncIdentificacion()
                            {
                                IdUsuarioCreacion = (int)(sqlDataReader["IdUsuario"] != DBNull.Value ? sqlDataReader["IdUsuario"] : 0),
                                Nombre = (string)(sqlDataReader["Nombre"] != DBNull.Value ? sqlDataReader["Nombre"] : string.Empty)
                            };
                            lstUsuarios.Add(objUsuario);
                        }
                    }
                }
    
            }
            catch (Exception ex) { objModErrorBase.MsgError = ex.Message; }
            finally { sqlDataReader?.Close(); }
            return lstUsuarios;
        }
    

    and these loaded objects can be sent to your view to render the browser and your user table. That I leave it to your form.

    <Paginador></Paginador>
    <tabla></tabla>
    <Paginador></Paginador>
    

    Just to give you some help, the page may be something like that

    @if (Model.TotalPaginas == 0)
    {
        <div>No se encontraron resultados</div>
    }
    else
    {
    <div>
        @if (Model.MostrarPaginacion)
        {
    
    
            <ul class="pagination" id="pagination">
                <li>
                    <a role="menuitem" tabindex="-1" id="aPagina" href="Model.Action, Model.Controller, new { Pagina = 1 }">
                        |<
                    </a>
                </li>
                @foreach (var pagina in Model.LstPaginas)
                {
    
                    if (Model.PaginaActual == pagina)
                    {
                        <li class="active">
                            <a role="menuitem" tabindex="-1" id="aPagina" href="@Url.Action(Model.Action, Model.Controller, new { Pagina = pagina })">
                                @pagina
                            </a>
                        </li>
                    }
                    else
                    {
    
                        <li>
                            <a role="menuitem" tabindex="-1" id="aPagina" href="@Url.Action(Model.Action, Model.Controller,  new { Pagina = pagina })">
                                @pagina
                            </a>
                        </li>
                    }
    
                }
                <li>
                    <a role="menuitem" tabindex="-1" id="aPagina" href="Model.Action, Model.Controller,  new { Pagina [email protected] }">
                        >|
                    </a>
                </li>
    
            </ul>
        }
    </div>
    }
    
        
    answered by 28.02.2017 в 18:47