0

I'm trying to use select to display a hidden input field. With option 2 I want to show the input field and with option 1 I want to hide it again.

Does anyone know what I need to change in the code?

Thanks in advance

function showFooField() {
            document.getElementById("nameFoo").style.display = "block";
        }
#nameFoo {
  display:none;
}
 <select onchange="showFooField()" name="foo" id="foo" class="form-control">
             <option value="1" selected>1</option>
             <option value="2">2</option>
  </select>
  
    <div id="nameFoo">
        <input id="name" required />
     <div>                                

1
  • You don't have any logic to check the option value or set display="none"; Commented May 25, 2021 at 19:55

2 Answers 2

3

You did not test the value before you changed the display.

I would use a class and toggle

window.addEventListener("load", () => { // when the page loads
  document.getElementById("foo").addEventListener("change", function() {
    document.getElementById("nameFoo").classList.toggle("hide", this.value === "1")
  })
})
.hide {
  display: none;
}
<select name="foo" id="foo" class="form-control">
  <option value="1" selected>1</option>
  <option value="2">2</option>
</select>

<div id="nameFoo" class="hide">
  <input id="name" required />
</div>

If you need to initialise:

window.addEventListener("load", () => { // when the page loads
  const sel = document.getElementById("foo");
  const input = document.getElementById("nameFoo");
  const toggle = function() {
    input.classList.toggle("hide", sel.value === "1")
  }
  sel.addEventListener("change", toggle)
  toggle(); // initialise
})
.hide {
  display: none;
}
<select name="foo" id="foo" class="form-control">
  <option value="1" selected>1</option>
  <option value="2">2</option>
</select>

<div id="nameFoo" class="hide">
  <input id="name" required />
</div>

Sign up to request clarification or add additional context in comments.

Comments

1

Run a check for the select value and you can manipulate the style from there

const el = document.getElementById("foo");
const inputEl = document.getElementById("nameFoo");
el.addEventListener("change", function() {
  if (this.value === "1") {
    inputEl.style.display = "none";
  }
  else {
    inputEl.style.display = "block";
  }
});
<select name="foo" id="foo" class="form-control">
  <option value="1" selected>1</option>
  <option value="2">2</option>
</select>

<div id="nameFoo" style="display: none">
  <input id="name" required />
<div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.