Radio button value with javascript

This tiny little javascript function can really be helpfull during your webdevelopment work. I used them very often when it requires for javascript validation or if there is need of AJAX work. I will try to explain in beginner mode so I can cover as many readers as I can, But I assume you must have some knowledge of HTML/Javascript Syntax.

[sourcecode language=”jscript”]

function checkOptionValue(inputObj){
var objLength = inputObj.length;
if(objLength == undefined){
if(inputObj.checked)
return inputObj.value;
else
return "";
}else{
for(var i = 0; i < objLength; i++) {
if(inputObj[i].checked) {
return inputObj[i].value;
}
}
}
return "";
}[/sourcecode]

Another way to find out if object exists or not

[sourcecode language=”jscript”]
function objExists(objToTest) {
if (null == objToTest) {
return false;
}
if ("undefined" == typeof(objToTest) ) {
return false;
}
return true;
}
[/sourcecode]

function explained

Pass the radio option as form object not the only the name of the radio button.
Example: function like checkOptionValue(document.form1.myoption);

var objLength = inputObj.length; – It gets the length of the radio options.
Example if there are 2 radio input like (male, female) its length will be 2.

if(objLength == undefined){ – Check if there is only one radio option, then length method will return undefined.

if(inputObj.checked) “checked” function returns true or false, true if option is checked/selected.

return inputObj.value; return the value of checked option.

Else return “”; if its not check return empty string.

Else do a loop based on the length of the radio object

Keep checking if any option found checked return its value.

Working Example

Which language you like the most?

Javascript

PHP

ASP .NET

NEXT: Setting the radio option value with javascript.

3 Comments

  1. Pete
    14th January 2009

    I’m not sure all of this is accurate – if a radio button group has 2 items (male, female) the length would be 1, not 2 – as javascript starts counting at 0 including 0 does it not?

    I continue to have issues patching someone else’s code because despite me checking for undefined (meaning only 1 radio button) I can never access the value of the undefined element.

    Reply
  2. Martha
    14th January 2009

    Thanks, help me so much…
    I was confused why my radio return “undefined” value..

    Reply
  3. ubaid
    14th January 2009

    Thanks i have searched lot why one radio button return undefined when it is checked and finally your script help me Thanks once again sir.

    Reply

Leave A Comment

To Top