Pure JS - display:block not working

I know this has been asked a million times but I swear, I just checked like 20 posts and nothing works...

This is my code:

When a use clicks on the "Email" option, the input element with an ID of "email" should show underneath it.

HTML

<select>
    <option selected disabled>Contact me by:</option>
    <option onclick="showInput()">Email</option>
</select>
<input class="email" id="email" placeholder="Email address" type="text" />

JS

function showInput() {
    document.getElementById("email").style.display = "block";
}

CSS

input#email {
    display: none;
}

Could someone explain to me how this is not working? I have a link to the JS file just before the body closing tag.

Answers:

Answer

Use the onChange event and move the event handler to the <select> element. Also added a value attribute to the <option> element to make text field identification simpler. And, finally, in the function, pass the select element to the event handler and grab the selected option from the select list.

<select onChange="showInput(this)">
    <option selected disabled>Contact me by:</option>
    <option value="email">Email</option>
</select>
<input class="email" id="email" placeholder="Email address" type="text" />

<script>

function showInput(sel) {
    var opt = sel.options[sel.selectedIndex].value
    document.getElementById(opt).style.display = "block"
}

</script>

JSFiddle

Now you can easily add more contact options:

<select onChange="showInput(this)">
    <option selected disabled>Contact me by:</option>
    <option value="email">Email</option>
    <option value="phone">Phone</option>
    <option value="address">Mail</option>
</select>
<input class="email"   id="email"   placeholder="Email address"   type="text" />
<input class="phone"   id="phone"   placeholder="Phone number"    type="text" />
<input class="address" id="address" placeholder="Mailing address" type="text" />
Answer

It's not a problem with display: none; at all. Your code doesn't work because it's impossible to attach onclick handler to OPTION element. Try this:

<select onchange="this.value === 'email' && showInput()">

It means "on selected option change check if email was selected and if it was, call showInput function".

You should add value attribute to OPTIONS, by the way.

See here.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.