change form controls with radio buttons

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
abushahin
Forum Commoner
Posts: 42
Joined: Wed Nov 25, 2009 12:35 pm
Location: london

change form controls with radio buttons

Post by abushahin »

hey, I was just wondering if anyone can give any tips on how I can achieve a change of form controls upon selection of a particular radio button i.e form has a textbox and one drop down list, when another radio button is clicked I want the form controls to change i.e add another drop down list or replace existing drop down dynamically.
jbulaswad
Forum Newbie
Posts: 14
Joined: Tue Mar 30, 2010 2:37 pm
Location: Detroit, Michigan, USA

Re: change form controls with radio buttons

Post by jbulaswad »

Abushahin,

Here is rudimentary example that can set you on your way:

Code: Select all

<html>
	<head>
		<title>Form Selection</title>
		<script type="text/javascript">
			/**
			 * Checks which radio is selected and displays the appropriate form
			 */
			function checkFormSelection() { 
				var arrRadios = document.getElementById('checkboxes').getElementsByTagName('input');
				for (var i = 0; i < arrRadios.length; i++) {
					document.getElementById(arrRadios[i].value).style.display = 'none';
					if (arrRadios[i].checked) {
						document.getElementById(arrRadios[i].value).style.display = 'block';
					}
				}
			}
			/**
			 * Set events on radio inputs
			 */
			window.onload = function () {
				var arrRadios = document.getElementById('checkboxes').getElementsByTagName('input');
				for (var i = 0; i < arrRadios.length; i++) {
					arrRadios[i].onclick = function () {
						checkFormSelection();
					};
				}
			};
		</script>
	</head>
	<body>
		<form action="POST" action="index.php" id="form">
			<div id="checkboxes">
				<label>Form Selection</label>
				<input type="radio" value="fruit" checked="checked" name="form_select" />
				<input type="radio" value="vegetable" name="form_select" />
			</div>
			<div id="fruit">
				<label for="fruit">Fruit</label>
				<input type="text" name="fruit" />
				<br/>				
				<label for="fruit_details">Details</label>
				<textarea name="fruit_details"></textarea>				
			</div>
			<div id="vegetable" style="display: none;">
				<label for="vegetable">Vegetable</label>
				<input type="text" name="vegetable" />
				<br/>
				<label for="vegetable_details">Details</label>
				<textarea name="vegetable_details"></textarea>
			</div>
		</form>
	</body>
</html>
Hope that helps!
abushahin
Forum Commoner
Posts: 42
Joined: Wed Nov 25, 2009 12:35 pm
Location: london

Re: change form controls with radio buttons

Post by abushahin »

Hey, that works very good, thank you.
Post Reply