# Show/hide text field depending on select option

I'm new with JavaScript and need your advice. The idea is to show/hide text field depending on select option. I have a working code, but I believe it could be more readable and better. What have I missed?

   <script type="text/javascript">
<!--
function showHide(){
var selectedValue =document.getElementById("choice_criteria_id").value;
var port = document.getElementById("id_port");
var port_range = document.getElementById("id_port_range");

if (selectedValue == "source_ip"){
port.style.display = "none";
port_range.style.display = "none";

} else if (selectedValue == "dest_ip"){
port.style.display = "none";
port_range.style.display = "none";

} else if (selectedValue == "port"){
port.style.display = "inline";
port_range.style.display = "none";

} else if (selectedValue == "port_range"){
port_range.style.display = "inline";
port.style.display = "none";
}
}

-->
</script>

• As we all want to make our code more efficient or improve it in one way or another, try to write a title that summarizes what your code does, not what you want to get out of a review. Please see How to get the best value out of Code Review - Asking Questions for guidance on writing good question titles. Mar 23 '16 at 13:58

You can use Conditional (ternary) Operator.

Syntax :

condition ? expr1 : expr2


Reformated code :

function showHide(){
var selectedValue =document.getElementById("choice_criteria_id").value;
document.getElementById("id_src_addr").style.display = (selectedValue == "source_ip") ? "inline" : "none";
document.getElementById("id_dst_addr").style.display = (selectedValue == "dest_ip") ? "inline" : "none";
document.getElementById("id_port").style.display = (selectedValue == "port") ? "inline" : "none";
document.getElementById("id_port_range").style.display = (selectedValue == "port_range") ? "inline" : "none";
}


# Example in CodePen

Use custom "map" object on the following scheme: {<element_id> : <dependent_value>}.
You can easily extend such object in case if there would be much more elements:

function showHide(){