Question

Why am I getting:

Uncaught TypeError: Object # has no method 'find' (anonymous function):8080/twolittlesheep/js/sizeColorDependancy.js:16 c.event.handleajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js:63 c.event.add.h.handle.oajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js:56

when I try to run a simple jquery script? The script falls at the line where I use the find method in the next jquery code snippet:

$(document).ready(function(){
  $("select#p_sizesId").change(function(){
   var $colorsSelect = $("select#p_colorsId")[0];
   $("select#p_colorsId")[0].find('option').remove().end().append('<option selected="selected" value="whatever">text</option>');
  });
});

In my head tag in the html I have:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<%-- <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script> --%>
<script type="text/javascript" src="js/sizeColorDependancy.js"></script>

I am using Google Chrome (together with Developer Tools).

All that I found as an explanation in another thread was that when using Chrome's developer tools, the problem arises. But I was running the code without using the Developer Tools and the same happened (the script didn't do anything => the error occurred).

Kind Regards,
Despot

Was it helpful?

Solution

When you do [0] you're getting the first element the selector matches as a DOM element, not a jQuery object which has .find(), just remove that [0], like this:

$(document).ready(function(){
  $("#p_sizesId").change(function(){
   $("#p_colorsId").find('option').remove().end().append('<option selected="selected" value="whatever">text</option>');
  });
});

A few other notes, when using a #id selector, don't prefix it unless absolutely needed, it slows things down. Also since IDs should be unique, there should be no need for getting the first element...the selector should only match 1 or 0 elements...if they're not unique, don't use IDs...use classes.

OTHER TIPS

Just make it into a jQuery object like this:

$($("select#p_colorsId")[0]).find('option')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top