D
D
devilwish2020-04-19 21:06:19
JavaScript
devilwish, 2020-04-19 21:06:19

How to limit the number of results in a search?

$(document).ready(function(){
   $('#search').keyup(function(){
      $('#result').html('');
      var searchField = $('#search').val();
      var expression = new RegExp(searchField,  "i");
      $.getJSON('goods.json', function(data){
        $.each(data, function(key, value){
          if(value.name.search(expression) != -1 || value.location.search(expression) != -1)
          {
            for (let i = 0; i < 10; i++){
            $('#result').append('<li style="list-style-type: none;margin:2px;border-bottom:1px solid #333;"><a href="'+key+'" title=""><img src="'+value.img+'" height:"40" width="40">'+value.name+'</a></li>')
          }
        }
        });
      
      });
   });
});

Displays the entire array, how to limit the number of output values?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RomanKudlatov, 2020-04-19
@RomanKudlatov

Oh god how I hate these brackets I hope I didn’t screw up anywhere

$(document).ready(function(){
   $('#search').keyup(function(){
      $('#result').html('');
      var searchField = $('#search').val();
      var expression = new RegExp(searchField,  "i");
      $.getJSON('goods.json', function(data){
        $.each(data, function(key, value){
        let i = 0;
        while(i<10)
          {
            if(value.name.search(expression) != -1 || value.location.search(expression) != -1)
            {
            $('#result').append('<li style="list-style-type: none;margin:2px;border-bottom:1px solid #333;"><a href="'+key+'" title=""><img src="'+value.img+'" height:"40" width="40">'+value.name+'</a></li>');
            i++;
            }
          }
        });
      });
   });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question