jQuery $(“#field”) is null?

2019-01-14 22:13发布

问题:

I have a selectbox with month periods in it.

Here is my code:

$(function(){ 
                        $("#ppsub_ppterm_id").change(function(){ 
                                        var term = this.options[this.selectedIndex].text; 
                                        if(term == "Eenmalig"){ 
                                                $(".idealtd").show(); 
                                        }else{ 
                                                $(".idealtd").hide(); 
                                                //$("#ppsub_amount option:selected").val('anders'); 
                                        } 
                        }); 
        }); 
<select name="ppsub_ppterm_id" class="ppsub_ppterm_id" 
id="ppsub_ppterm_id" style="width: 100px; font-size: 11px;"> 
                                                <option value="M">Maand</option> 
                                                <option value="K">Kwartaal</option> 
                                                <option value="H">Halfjaar</option> 
                                                <option value="J">Jaar</option> 
                                                <option selected value="E">Eenmalig</option> 
                                        </select> 

But when i load my page i staight away get an error:

$("#ppsub_ppterm_id") is null

Line 17

Any ideas?

回答1:

Sounds like JQuery isn't loading properly. Which source/version are you using?

Alternatively, it could be namespace collision, so try using jQuery explicitly instead of $. If that works, you may like to use noConflict to ensure the other code that's using $ doesn't break.



回答2:

chane '$' by jQuery for example:

$("#myId") -> jQuery("#myId")

It works



回答3:

Even if jQuery couldn't find the element, it wouldn't be null - it would be an empty jQuery object.

Are you sure jQuery is loaded? Is it possible that another JavaScript library you're using is causing conflicts?



回答4:

you have "ppsub_ppterm_id" as a class, name, id etc...

You need to pick ONE and select on it. There is no need for ID, NAME, CLASS to all have the same values.

You're probably confusing the hell out of jQuery.

<a id="ppsub_ppterm_id"> = $("#ppsub_ppterm_id")

<a class="ppsub_ppterm_id"> = $(".ppsub_ppterm_id")

<a name="ppsub_ppterm_id">  = $("*[name=ppsub_ppterm_id]")

Pick a way and go with it, but take out all those redundant attributes.



回答5:

Make sure you're running your jQuery code after the document is loaded:

$(document).ready(function() { /* put your stuff here */ });

Also make sure you have no other controls with the id "ppsub_ppterm_id" on your HTML page.

Those are the first things I would check.