Search code examples
javascripthtmlonchangegetelementbyidonkeyup

How to create a link based on textbox value?


I'm trying to change the href of my link based on whats in the textbox with id="serie". As you can see, Firefox tells me that el is null. What did go wrong here?

(Upper part is Page, Middle part the debug-console and the lower part is my source code)

<html>
    <head>
        <script>
            var el = document.getElementById('serie');
            var lnk = document.getElementById('link');
            el.onchange = el.onkeyup = function() {lnk.href = "http://bs.infinibrain.net/" + userInput + ".xml";};
        </script>
    </head>
    <body>
        <h1>Anleitung</h1>
        1. <a href="index.xml" target="_blank">Hier</a> die id eurer Serie suchen (Leider sind noch nicht alle aufgelistet)<br/>
        2. dann id hier eingeben: <input id="serie" /><br/>
        3. und <a href="#" id="link">hier</a> die links raussuchen <br/>
    </body>
</html>

Solution

  • You are trying to access the element even before its loaded. Place your script at the end of your body.

        <html>
        <body>
            <h1>Anleitung</h1>
            1. <a href="index.xml" target="_blank">Hier</a> die id eurer Serie suchen (Leider sind noch nicht alle aufgelistet)<br/>
            2. dann id hier eingeben: <input id="serie" /><br/>
            3. und <a href="#" id="link">hier</a> die links raussuchen <br/>
            <script>
                var el = document.getElementById('serie');
                var lnk = document.getElementById('link');
                el.onchange = el.onkeyup = function() {lnk.href = "http://bs.infinibrain.net/" + userInput + ".xml";};
            </script>
        </body>
    </html>
    

    Also you didnot define userInput, it should be el.value:

    lnk.href = "http://bs.infinibrain.net/" + el.value + ".xml";