a.smith
a.smith

Reputation: 315

on dropdown select value show hidden input field

This has definitely been covered before and im sure it will again but none of the examples ive found are helping me.

I have a dropdown field, when option 2(Admin) is selected i want to display a text input type that is otherwise hidden.

const ac = document.getElementById("admin_code");
ac.style.display = "none";

function toggleDropdown(selObj){
  ac.style.display = selObj.value === "Admin" ? "block" : "none";
}
<label>User Type:</label> <select id="userType" name="userType" id="userType" onchange='toggleDropdown(this);' required>
<option value="" selected>Select User Type</option>
<option value="Client">Client</option>
<option value="Admin">Admin</option>
<option value="Staff">Staff</option>
</select>
<br>
<div id="admin_code">
<label>Person Code:</label> <input type="text" name="adminCode" 
id="adminCode" placeholder="000001">
</div>

Currently when i go into the page with this on my admin_code div shows from the start. I have tried changing the style.display values both to none to see if it is even being called but it seems it is not.

Upvotes: 0

Views: 1347

Answers (2)

crokadilekyle
crokadilekyle

Reputation: 100

This worked for me. First I set the initial style for div#admin_code to "display: none;"

Then I changed your function slightly

    function toggleDropdown(){
    let value = document.querySelector('select').value;
      if (value=="Admin") {
         document.getElementById("admin_code").style.display = "block";
      } else {
          document.getElementById("admin_code").style.display = "none";
     }
    }
    <label>User Type:</label> <select id="userType" name="userType" id="userType" onchange='toggleDropdown();' required>
                <option value="" selected>Select User Type</option>
                <option value="Client">Client</option>
                <option value="Admin">Admin</option>
                <option value="Staff">Staff</option>
    </select>
    <br><div id="admin_code" style="display: none;">
    <label>Admin Code:</label> <input type="text" name="adminCode" id="adminCode" >
    </div>

Upvotes: 0

symlink
symlink

Reputation: 12209

Pass the this keyword into your callback function:

const ac = document.getElementById("admin_code");
ac.style.display = "none";

function toggleDropdown(selObj) {
  ac.style.display = selObj.value === "Admin" ? "block" : "none";
}
<label>User Type:</label>
<select id="userType" name="userType" id="userType" onchange='toggleDropdown(this);' required>
  <option value="" selected>Select User Type</option>
  <option value="Client">Client</option>
  <option value="Admin">Admin</option>
  <option value="Staff">Staff</option>
</select>
<br>
<div id="admin_code">
  <label>Admin Code:</label> <input type="text" name="adminCode" id="adminCode">
</div>

Upvotes: 2

Related Questions