Skip to content Skip to sidebar Skip to footer

Radio Button Producing Undefined Value In Javascript Function

I am trying to send the value of a radio button to a javascript function. Eventually the function will do more but my testing it has come to a dead end because I keep getting a ret

Solution 1:

The access path you actually want is:

var el = document.forms["jobView"].elements["sales"];

The straight dot chain (document.jobView.sales) makes an implicit call to the "all" collection, which will only work in IE. (Yes, I know that Firefox returns an identical-looking string in its error console when things go wrong, but you can't actually use it in your own code.) getELementsByTagName() and getElementsByName() will work just fine, but then you need to ensure that the elements in the returned collection are the ones you actually want. (Assume that a time will come when you want to create more than one form on the page, and that field names will collide. It will never happen, of course, unless you fail to make that assumption out of the gate, whereupon another developer will immediately add a second form to the page you just committed.)


Solution 2:

Try with document.getElementsByTagName like this:

 function jobWindow(){
  var myvalue;
  var el = document.getElementsByTagName('input');

  for( i = 0; i < el.length; i++ ){
   if (document.forms['jobView'].el[i].type === 'radio' && document.forms['jobView'].el[i].name === 'sales')
   {
     if(document.forms['jobView'].el[i].checked == true )
     {
       myvalue = document.forms['jobView'].el[i].value;
       break;
     }
   }
  }
  alert( "val = " + myvalue );
 }

Note also that your break line never executed because you were missing curly brackets:

if( document.jobView.sales[i].checked == true )
{
   target = document.jobView.sales[i].value;
   break;
}

Solution 3:

change document.jobView.sales to document.getElementsByName('sales')


Solution 4:

throw some debugging in there. for example put an alert() inside the for() statement to make sure it is getting a definition for document.jobView.sales.length.

If it doesn't make the alert, you can almost bet document.jobView.sales.length is undefined.

You can then do try { var length = document.jobView.sales.length; } catch(e) { alert(e); } to verify this.

If you verify that document.jobView.sales.length isn't being defined, you may have to use document.getElementsByTagName, and loop through them instead of document.jobView


Post a Comment for "Radio Button Producing Undefined Value In Javascript Function"