Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display div if a specific select option value is selected

Tags:

javascript

I am trying to display a div if user select a specific option value from a select drop down list.

Example:

The select drop down list consist of dynamic names fetched from the database and also one static or permanent name at the bottom of the list called "Admin"

If user select an option that's not "Admin", a div containing certain form element is shown else if the user select "Admin" that div remain hidden

Here is my code:

Javascript -

<script language="javascript">

function admSelectCheck(nameSelect)
{
    if(nameSelect){
        admOptionValue = document.getElementById("admOption").value;
        if(admOptionValue != 0){
            document.getElementById("admDivCheck").style.display = "";
        }
        else{
            document.getElementById("admDivCheck").style.display = "none";
        }
    }
    else{
        document.getElementById("admDivCheck").style.display = "none";
    }
}

</script>

HTML -

<select id="getFname" onchange="admSelectCheck(this.select);">
<option value="1">Jay</option>
<option value="4">Sam</option>
<option id="admOption" value="0">Admin</option>
</select>


<div id="admDivCheck" style="display:none;">
admin selected
</div>

Would be glad getting help with this.

like image 641
John Avatar asked May 23 '13 11:05

John


2 Answers

Using this.select is incorrect.

Here is the correct code:

HTML

<select id="getFname" onchange="admSelectCheck(this);">
<option value="1">Jay</option>
<option value="4">Sam</option>
<option id="admOption" value="0">Admin</option>
</select>


<div id="admDivCheck" style="display:none;">
admin selected
</div>

JS

function admSelectCheck(nameSelect)
{
    console.log(nameSelect);
    if(nameSelect){
        admOptionValue = document.getElementById("admOption").value;
        if(admOptionValue == nameSelect.value){
            document.getElementById("admDivCheck").style.display = "block";
        }
        else{
            document.getElementById("admDivCheck").style.display = "none";
        }
    }
    else{
        document.getElementById("admDivCheck").style.display = "none";
    }
}

See the demo on JSFiddle.

like image 101
Aziz Shaikh Avatar answered Sep 20 '22 15:09

Aziz Shaikh


I think you need like this

Just Change this line:

JS

admOptionValue = document.getElementById("getFname").value;
//alert(admOptionValue);

if(admOptionValue == 0){
     document.getElementById("admDivCheck").style.display = "";
}
else{
     document.getElementById("admDivCheck").style.display = "none";
 }

And also in HTML

onchange="admSelectCheck(this);"

see Demo

like image 26
Dhaval Marthak Avatar answered Sep 21 '22 15:09

Dhaval Marthak