Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show input field only if a specific option is selected

I'm trying to make a form which checks if a certain option is selected from a "select" tag. Here is my current HTML:

<select onchange="yesnoCheck()">
    <option id="noCheck" value="">Valitse automerkkisi</option>
    <option id="noCheck" value="lada">Lada</option>
    <option id="noCheck" value="mosse">Mosse</option>
    <option id="noCheck" value="volga">Volga</option>
    <option id="noCheck" value="vartburg">Vartburg</option>
    <option id="yesCheck" value="other">Muu</option>
</select>

This is the div element which should become visible after "Muu" is selected:

<div id="ifYes" style="display: none;">
    <label for="car">Muu, mikä?</label> <input type="text" id="car" name="car" /><br />
</div>

And here is the JavaScript I'm trying to use:

<script type="text/javascript">
    function yesnoCheck() {
        if (document.getElementById("yesCheck").checked) {
            document.getElementById("ifYes").style.display = "block";
        } else {
            document.getElementById("ifYes").style.display = "none";
        }
    }
</script>

But it's not working...

like image 890
user1589375 Avatar asked Mar 28 '15 19:03

user1589375


People also ask

How do you check if a option is selected or not?

$('#mySelectBox option'). each(function() { if ($(this). isChecked()) alert('this option is selected'); else alert('this is not'); });

How Show hide DIV when select options are clicked in jQuery?

If you want to hide/show div on dropdown selected, use the jQuery hide() and show(). Before you perform hide or show div on dropdown selection, you need to hide them first using CSS display:none.


2 Answers

here you go:

function yesnoCheck(that) {
    if (that.value == "other") {
  alert("check");
        document.getElementById("ifYes").style.display = "block";
    } else {
        document.getElementById("ifYes").style.display = "none";
    }
}
<select onchange="yesnoCheck(this);">
    <option value="">Valitse automerkkisi</option>
    <option value="lada">Lada</option>
    <option value="mosse">Mosse</option>
    <option value="volga">Volga</option>
    <option value="vartburg">Vartburg</option>
    <option value="other">Muu</option>
</select>

<div id="ifYes" style="display: none;">
    <label for="car">Muu, mikä?</label> <input type="text" id="car" name="car" /><br />
</div>
like image 175
Josephus87 Avatar answered Sep 20 '22 09:09

Josephus87


Check out: Display div if a specific select option value is selected

Also don't use ID use data attributes or value to check comparison.

like image 34
Mike Avatar answered Sep 19 '22 09:09

Mike