Sunday, November 14, 2010

How do you output the value from a radio button in html?

For example, if I click on the radio button for ';Male';, how can I get the word ';Male'; to be outputted on to the page after I submit the form? Is it concatenation?How do you output the value from a radio button in html?
To process any responses to a form you need to use a script.





The script can be embedded in the page (such as javascript), or it can reside on the server (such as php). These are known as client-side and server-side scripts.





Client side scripts are more immediate - they don't require the page to be reloaded from the server. On the other hand not everyone has javascript enabled.





The following, which should be in a file called radio.php, illustrates the use of both client-side and server-side scripting:





%26lt;!DOCTYPE html PUBLIC ';-//W3C//DTD HTML 4.01 Transitional//EN';


';http://www.w3.org/TR/html4/loose.dtd'; %26gt;


%26lt;html lang='en'%26gt;


%26lt;head%26gt;


%26lt;meta http-equiv='Content-type' content='text/html;charset=UTF-8'%26gt;


%26lt;title%26gt;Radio Button Example%26lt;/title%26gt;


%26lt;script type=';text/javascript';%26gt;


function getGender(form) {


var g = form.gender;


var gender = '';


for (var i = 0; g.length %26gt; i; i++) {


if (g[i].checked===true) {


gender = g[i].value;


}


}


var response = '';


if (gender == '') {


response = 'Please Answer.';


} else {


response = 'You are ' + gender + '.';


}


document.getElementById( 'answer' ).innerHTML = response;


return false;


}


%26lt;/script%26gt;


%26lt;/head%26gt;


%26lt;body%26gt;


%26lt;h1%26gt;Radio Button Example%26lt;/h1%26gt;


%26lt;p%26gt;Please state your gender. %26lt;/p%26gt;


%26lt;form method=';get'; action=';radio.php'; name=';visitor'; onsubmit=';return getGender(this);';%26gt;


%26lt;label%26gt;%26lt;input type=';radio'; name=';gender'; value=';Male'; %26gt; Male %26lt;/label%26gt;








%26lt;label%26gt;%26lt;input type=';radio'; name=';gender'; value=';Female';%26gt; Female %26lt;/label%26gt;








%26lt;input type=';submit'; value=';continue'; %26gt;


%26lt;/form%26gt;


%26lt;p id=';answer';%26gt;


%26lt;?php


$gender = $_REQUEST['gender'];





if ($gender == ';';)


echo ';Please Answer';;


else


echo ';You are '; . $gender;


?%26gt;


%26lt;/p%26gt;


%26lt;/body%26gt;


%26lt;/html%26gt;





For the client-side scripting a javascript function ( getGender() ) is defined in a script tag.





This is activated by the form tag's onsubmit attribute. By having the function and the attribute return false, the form's action is not taken. Instead the function undertakes the writing of data to the page.





For more on the script and form tags see: http://www.html-tags-guide.com/html-scri鈥?/a> and http://www.html-tags-guide.com/html-form鈥?/a>

No comments:

Post a Comment