Search code examples
javascripthtmldrop-down-menuhrefappendchild

Adding hyperlinks with javascript to html drop down div


I am trying to add more links to this drop down menu, the menu itself works and the links I've provided works as well, the problem is that when I try to add links through a Javascript file using appendChild, nothing seems to be happening. Also the form handling is successful in other codes, the only thing wrong is what is described above.

dropdown.html

<body>
<form id="aform">
  URL:<br>
  <input type="text" name="URL" id="URL">
  <br>
  Bookmark Name:<br>
  <input type="text" name="bookmarkname" id="bookmarkname">
  <br><br>
  <input type="submit" id="formsubmit">
</form> 
<div class="dropdown">
  <button class="dropbtn" id="dropdown">Links</button>
  <div id="myDropdown" class="dropdown-content">
    <a href="https://youtube.com">Youtube</a>
    <a href="https://www.amazon.com">Amazon</a>
    <a href="https://www.yahoo.com">Yahoo</a>
  </div>
</div>
<script src="dropdown.js"></script>

dropdown.js

function retrieveFormData() {
            var URL = document.getElementById("URL").value;
            var Bookmarkname = document.getElementById("bookmarkname").value;
            var y = document.getElementById("myDropdown");
            var aTag = document.createElement('a');
            aTag.appendChild(document.createTextNode(Bookmarkname))
            aTag.href = URL;
            y.appendChild(aTag);
}

So I try to append new to 'y', but nothing happens in the actual drop down menu, no is added.


Solution

  • That is because you are using a submit button. The submit button tells the browser to send the contents of the form to the server side.

    What you want to do is change the submit button to a regular button and add an onclick event.

    <body>
    <form id="aform">
      URL:<br>
      <input type="text" name="URL" id="URL">
      <br>
      Bookmark Name:<br>
      <input type="text" name="bookmarkname" id="bookmarkname">
      <br><br>
      <input type="button" id="formsubmit" onclick="retrieveFormData();" value="Submit">
    </form> 
    <div class="dropdown">
      <button class="dropbtn" id="dropdown">Links</button>
      <div id="myDropdown" class="dropdown-content">
        <a href="https://youtube.com">Youtube</a>
        <a href="https://www.amazon.com">Amazon</a>
        <a href="https://www.yahoo.com">Yahoo</a>
      </div>
    </div>
    <script src="forminput.js"></script>