Showing Different Input Boxes Based on Select Value

Sometimes it is useful to hide some input boxes when they are not needed. This simple script hides unnecessary inputs and shows the ones that are needed.

Different Input Boxes Screen Shot

function selectChanged(sel)
{
	if(sel.selectedIndex==0)
	{
		document.getElementById('input-id-1').style.display='';
		document.getElementById('input-id-2').style.display='none';
	}
	else
	{
		document.getElementById('input-id-1').style.display='none';
		document.getElementById('input-id-2').style.display='';
	}
}

Here is the full HTML page for testing purposes. You will need to modify it to your needs:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function selectChanged(sel)
{
	if(sel.selectedIndex==0)
	{
		document.getElementById('input-id-1').style.display='';
		document.getElementById('input-id-2').style.display='none';
	}
	else
	{
		document.getElementById('input-id-1').style.display='none';
		document.getElementById('input-id-2').style.display='';
	}
}
</script>
</head>
<body>
<form action="" method="post">
<table>
<tr><td>Input-1</td><td><input name="input-1" type="text" /></td></tr>
<tr><td>Input-2</td><td><input name="input-2" type="text" /></td></tr>
<tr><td>Input Select</td><td><select name="select-name" onchange="selectChanged(this)"><option>Option 1</option><option>Option 2</option></select></td></tr>
<tr id="input-id-1"><td>Input-3</td><td><input name="input-3" type="text" value="One" /></td></tr>
<tr id="input-id-2" style="display:none"><td>Input-4</td><td><input name="input-4" type="text" value="Two" /></td></tr>
<tr><td colspan="2" align="right"><input name="submit" type="submit" value="Submit" /></td></tr>
</table>
</form>
</body>
</html>

One thought on “Showing Different Input Boxes Based on Select Value

Leave a Reply

Your email address will not be published. Required fields are marked *