0

I want to reveal a hidden part of an input form when a specific value is chosen in an earlier part.

Why does this Javascript work

  function unhideRecipient() {
    var recipDiv = document.getElementById("recipientDetails");
    // recipient1 = document.getElementById("recipient1");   // ?????
    if (recipient1.value == "0") {                           // ?????
      recipDiv.style.display = "block";
    } else {
      recipDiv.style.display = "none";
    }
  }

Given this HTML

<form>
  <label>Recipient:</label>
  <select name="recip1" id="recipient1" onchange="unhideRecipient()">
    <option value="1">Alice Doe</option>
    <option value="2">Bobby Poe</option>
    <option value="3">Clive Roe</option>
    <option value="0">Other ...</option>
  </select>
  <br />
  <div id="recipientDetails">
    <label>Name:</label>       <input type="text"> <br />
    <label>StreetName:</label> <input type="text"> <br />
    <label>City:</label>       <input type="text"> <br />
  </div>
</form>

With this style

  label { display: inline-block; width: 6em; text-align: right; }
  div#recipientDetails { display: none; }

I had expected to need the commented out variable assignment in the Javascript but it seems to work just using the elements id attribute value as if it were an object name.

Am I misunderstanding - and where can I read more about this?

https://codepen.io/anon/pen/ydgpML

RedGrittyBrick
  • 3,827
  • 1
  • 30
  • 51
  • Browsers put references to DOM elements with id values into the global scope as variables (`window` properties). It's a thing that IE started a long time ago. It's a terrible idea but here we are. – Pointy Jun 20 '19 at 17:20
  • 1
    Note: the `
    ` tag does not use and does not need a closing slash and never has in HTML.
    – Rob Jun 20 '19 at 17:20

0 Answers0