DELION
DELION

Reputation: 127

JavaScript - Uncaught TypeError: Cannot read property 'search' of undefined

When I execute my Javascript I'm getting this error:

Uncaught TypeError: Cannot read property 'search' of undefined

And I don't know how do fix it and why that is shown.

I have objects inside an array,

example:

AsukohaArray = [{"Punkt":[[58.1056],[23.2589]],
                    "name":"Haapsalu Raamat",
                    "PunktiID": 23}];

My code

$(document).ready(function() {
  $("input[type='search']").keyup(function() {
    var searchTerm = $(this).val();
    var myExp = new RegExp(searchTerm, "i");
    var output = "<ul id='result'>";
    $.each(AsukohaArray, function(key, val) {
      //console.log(val.name);
      if ((val.name).search(myExp) != -1) {
        output += '<li>';
        output += val.name;
        output += '</li>';
      }
    });
    console.log(output);
    output += "</ul>";
    $('div#update').html(output);
  });
});

HTML

<ons-page id="my-page">
    <ons-toolbar>
        <div class="left">
            <ons-toolbar-button ng-click="menu.toggleMenu()"><ons-icon icon="ion-navicon" style="font-size: 32px; width: 1em;"></ons-icon></ons-toolbar-button>
        </div>

        <div class="center">Kaardi vaade</div>
    </ons-toolbar>
    <div id="nupuriba">
    <input type="search" class="search-input" id="#search">
    </div>
    <div id="update"></div>
    <div id="map-canvas">
    </div>
</ons-page>

When I insert "Haapsalu" then results are:

Haapsalu piiskopilinnus Haapsalu Kunstikool Haapsalu Raamat Uncaught TypeError: Cannot read property 'search' of undefined

I have searched that error, but no result, haven't found nothing similar.

Upvotes: 3

Views: 38092

Answers (2)

renakre
renakre

Reputation: 8291

Can you try

   if(val.indexOf(myExp) != -1){

instead of

   if(val.search(myExp) != -1){

Upvotes: 0

Laurentiu Petrea
Laurentiu Petrea

Reputation: 126

Is your "val" (item from the array) a primitive data type, or is it an object containing the attribute "name"? If your val is let's say a String type, you should "search" directly into it. Your error suggests that "val" does not contain an attribute called "name".

Also, since you are using a RegExp, there, you should probably go with

if( val.match(myExp) > 0 )

or even better, if you only care about a boolean result,

if ( val.test(myExp) )

If I am wrong, and your .name attribute exists, if it's a string, just use it directly without the parenthesis:

if( val.name.test(myExp) )

Upvotes: 1

Related Questions