Search code examples
javascripthtmlformsurl-parameters

Cannot set Dropdown Selected Index: Uncaught TypeError: Cannot set properties of null (setting 'selectedIndex')


It should be very easy but don't figure out where the problem is. I need to get the value from an url parameter then make the the dropdown list's option selected based on index number. The URL is something like this:

..../page.html?tid=5

HTML is here

<select id="form-dropdown-field">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
    <option value="D">D</option>
    <option value="E">E</option>
    <option value="F">F</option>
    <option value="G">G</option>
    <option value="H">H</option>
</select>

This is the JS part:

        const queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString);
        const tid = parseInt(urlParams.get('tid')) - 1;
        console.log(tid);

        document.getElementById("form-dropdown-field").selectedIndex = tid.toString() ;

I get the url parameter value with no problem. It shows 4 in console.log() output. But I get the following error:

Uncaught TypeError: Cannot set properties of null (setting 'selectedIndex')

UPDATE:

My script is already in the <head><script>...</script></head> tags as @Mina suggests in the comment. And I added the defer attribute to <script> tag.


Solution

  • It is not about defer or something else.

    I put the js code part after the select tag then it now works.

    <!DOCTYPE html>
    <html>
        <head>
        </head>
        <body>      
            <select id="form-dropdown-field">
                <option value="A">A</option>
                <option value="B">B</option>
                <option value="C">C</option>
                <option value="D">D</option>
                <option value="E">E</option>
                <option value="F">F</option>
                <option value="G">G</option>
                <option value="H">H</option>
            </select>
            <script>
                const urlParams = new URLSearchParams(window.location.search);
            
                const tid = parseInt(urlParams.get('tid')) - 1;
                    
                document.getElementById("form-dropdown-field").selectedIndex = tid;
            </script>
        </body>
    </html>