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.


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 "";
}

Another way to find out if object exists or not

function objExists(objToTest) {
if (null == objToTest) {
return false;
}
if ("undefined" == typeof(objToTest) ) {
return false;
}
return true;
}

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.

Tags: , , , , , ,

2 Comments »

  1. 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.

    Comment by Pete — April 27, 2009 @ 18:55

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

    Comment by Martha — May 14, 2009 @ 08:58

RSS feed for comments on this post. TrackBack URL

Leave a comment