john
john

Reputation: 3

Jquery cannot read property of null error

Hi I'm learning Jquery and I can't get it to run a function - code below.

I've set up a simple select box and then tried to add an on change event to it. Originally I tried with a .change but then I read that using the method shown is better since it doesn't rely on the element being available at the start.

I'm just getting an error of Uncaught TypeError: Cannot read property 'find' of null. I've not used jsfiddle before but I've tried to set one up here https://jsfiddle.net/2L6z3fdm/

Help!

            <select id="roomCapacity" >
              <option value="volvo">Volvo</option>
              <option value="saab">Saab</option>
              <option value="mercedes">Mercedes</option>
              <option value="audi">Audi</option>
            </select>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
            <script> 
             $( "#roomCapacity" ).on("change",function(){
                        roomLayoutBox = ["Volvo","Ford"];
                        console.log(this.value);
                        $('#roomStyle').find('option:not(:first)').remove();

                    });
            </script>

Upvotes: 0

Views: 13714

Answers (2)

wjvander
wjvander

Reputation: 601

Your code should read as follows

$("#roomCapacity").on("change",function(){
  roomLayoutBox = ["Volvo","Ford"];
  console.log(this.value);
  $("#roomCapacity").find('option:not(:first)').remove();
});

roomStyle does not exist as the id for any element.

Upvotes: 1

AkshayJ
AkshayJ

Reputation: 769

$("#roomCapacity").on("change",function(){
  roomLayoutBox = ["Volvo","Ford"];
  console.log(this.value);
  $("#roomCapacity").find('option:not(:first)').remove();
});

roomStyle doesnt exist in the current context :) You can also use

$(this).find('option:not(:first)').remove();

Upvotes: 1

Related Questions