jQuery issue getting error -> Cannot read property 'match' of null

时间:2018-02-03 08:19:17

标签: jquery

$(document).ready(function()
{
    $('#search').keyup(function() {
        var searchField = $('#search').val();
        if(searchField.length >=3 )
        {

            var myExp = new RegExp(searchField, "i");

            $.get('products.json', function(data) 
            {
                var output = '<ul class="searchresults">';
                $(data).each(function(key, val)
                {
                    var name = val.name;
                    if( name.match(myExp) != -1)
                    {
                        output += '<li>' + val.name + '</li>';
                    }

                });
                output += '</ul>';
                alert(output)
                $('#update').html(output);
            }); //get 
        }
    });
});

I have try to everything but not getting out of this error. i have tried with .search and .test but still the same. any help will be appreciated. Thanks

1 个答案:

答案 0 :(得分:0)

Try this

$(document).ready(function(){

    $('#search').keyup(function() {
        var searchField = $('#search').val();
        if(searchField.length >=3 ){

            var myExp = new RegExp(searchField, "i");

            $.get('products.json', function(data) {

                var output = '<ul class="searchresults">';
                $(data).each(function(key, val){

                    var name = val.name;
                    if(name && name.toString().match(myExp)['index'] != -1){
                        output += '<li>' + val.name + '</li>';
                    }

                });
                output += '</ul>';

                alert(output)
                $('#update').html(output);
            }); //get 
        }
    });
});