Javascript – Uncaught TypeError: Cannot read property ‘length’ of null JSON-JQUERY

javascriptjqueryjson

Its function have problems and show for console
Uncaught TypeError: Cannot read property 'length' of null
and cant understant why

function shownameplaylist(){
$.getJSON( "js/json/nameplaylist.json", function( data ) {
    var items = [];
    $.each( data, function( key, value ) {
        $('#nameplaylist').append('<option>'+value.title+'</option>')
    });
    $('.nameplaylist option:first-child').attr("selected", "selected");
    nameplaylist=$( ".nameplaylist option:selected" ).text();
    console.log(nameplaylist.length);
    if(nameplaylist.length==0){
        $('#nameplaylist').css('display','none');
        $('#delplaylist').css('display','none');
    }
}).done(function(){ // If the AJAX call encountered an error
        showplaylist();
    })
    .fail(function(){ // If the AJAX call encountered an error
        console.log('no load nameplaylist');
        $('#nameplaylist').css('display','none');
        $('#delnamelist').css('display','none');
        $('#delplaylist').css('display','none');

    });
}

Best Answer

You're using two different selectors for "nameplaylist", #nameplaylist and .nameplaylist. The first implies an element with an ID of "nameplaylist" and the second implies an element with a class of "nameplaylist".

$('#nameplaylist') and $('.nameplaylist') will not select the same element unless your element has both an id and class of "nameplaylist":

<elem id="nameplaylist" />       <!-- $('#nameplaylist') -->
<elem class="nameplaylist" />    <!-- $('.nameplaylist') -->

Determine which one you're actually using and modify your selectors accordingly.

Looking at your code, I imagine your fix will simply be to change lines 7 and 8 to:

$('#nameplaylist option:first-child').attr("selected", "selected");
nameplaylist=$( "#nameplaylist option:selected" ).text();
Related Topic