Search code examples
javascripthtmldatalist

Why doesn't the link generate where <span id="navigationLink"></span> indicates


I've been trying to obtain the outcome of this code for quite a while but it just doesn't seem to work. I want a link to be generated below but when I preview the script, the link doesn't seem to show up. I am genuinely clueless as to how or which parts of the script are wrong and would particularly appreciate anyone's help on this:

<DOCTYPE html>
<html>
<head>
    <script>
        function updateNavigationLink() {
            var link = "https://maps.google.com/maps?saddr=" +
                encodeURIComponent(document.getElementById("start").value) +
                "&daddr=" + encodeURIComponent(document.getElementById("end").value);
            document.getElementById("navigationLink").textContent = link; 
        }
    </script>

    <meta charset="utf-8">
    <title>ISHGUIDE</title>
</head>
    <link rel="stylesheet" type="text/css" href="style.css">

    <div class=naviselection>
        Start:
        <input type='text' list='start' />
        <datalist id="start" onchange="updateNavigationLink()">  
            <option value="The International School of The Hague, Wijndaelerduin 1, 2554 BX Den Haag">School</option>
            <option value="Centrum, Den Haag">City Center</option>      
        </datalist> 
        End:
        <input type="text" list="end" />
        <datalist id="end" onchange="updateNavigationLink()">
            <option value="The International School of The Hague, Wijndaelerduin 1, 2554 BX Den Haag">School</option>
            <option value="Centrum, Den Haag">City Center</option>      
        </datalist>
    </div>

    <div class=Finallink>
        <span id="navigationLink"></span>         
    </div>
</html>

Solution

  • A very straight forward way of doing it with minimal change to you code will be :

    1. Give the onchange to your input
    2. Give the start and end ids to your input

    Just change your input bloks to this

    <input type='text' list='startinput' id="start" onchange="updateNavigationLink()" />
        <datalist id="startinput" >  
            <option value="The International School of The Hague, Wijndaelerduin 1, 2554 BX Den Haag">School</option>
            <option value="Centrum, Den Haag">City Center</option>      
        </datalist>   
    <input type="text" id="end" list="endinput" onchange="updateNavigationLink()"/>
            <datalist id="endinput" >
                <option value="The International School of The Hague, Wijndaelerduin 1, 2554 BX Den Haag">School</option>
                <option value="Centrum, Den Haag">City Center</option>      
            </datalist>
    

    Also you might want to change this span

    <span id="navigationLink"></span>
    

    to an a tag with href

    <a id="navigationLink"></span>
    

    and when you set the value you'll do this

    document.getElementById("navigationLink").href = link;