Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 139805

How to show error if name does not exist in json file?

$
0
0

I have stuck how to show error if name is not exist in json file. I have tried if(searchField != value.name.search(expression)) and if(searchField != value.name) but its not working.Here is my code what I have tried. Please help. Thanks

js code

$(document).ready(function() {
  $('.dropbox').css('border', 'none');
  $.ajaxSetup({
    cache: false
  });
  $('#search').keyup(function() {
    $('#searchResult').html('');
    $('#state').val('');
    var searchField = $('#search').val().trim();
    var expression = new RegExp(searchField, "i");
    console.log(expression);
    $.getJSON('result.json', function(data) {
      $.each(data, function(key, value) {
        if (value.name.search(expression) != -1) {
          $('.dropbox').css('border', '1px solid #EBEDF8');
          $('#searchResult').append('<ul><li><div class="img_c"><img src="' + value.imgURL + '" alt="Profile Pic"></div><div class="content-box"> ' + value.name + '|<span>' + value.city + ', ' + value.state + '</span></div></li></ul>');
        }
        if (searchField === '') {
          $('#searchResult').html('<div class="message">No matches found</div>');

        }
      });
    });
  });
  $('#searchResult').on('click', 'li', function() {
    var click_text = $(this).text().split('|');
    $('.dropbox').css('border', 'none');
    $('#search').val($.trim(click_text[0]));
    $("#searchResult").html('');
  });
});

HTML

<div class="dropbox">
    <div id="searchResult"></div>
</div>

result.json file

[
 {
     "id":1,
      "name":"John",
      "city":"London City",
      "state":"London",
      "imgURL":"images/pic.svg"

 },
 {
    "id":2,
     "name":"Mathew",
     "city":"New York City",
     "state":"NY",
     "imgURL":"images/pic.svg"

},
{
     "id":3,
      "name":"Jackson",
      "city":"Washington",
      "state":"DC",
      "imgURL":"images/pic.svg"

 }

]

Viewing all articles
Browse latest Browse all 139805

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>