#1
  1. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    2,687
    Rep Power
    171

    Can't access radio button value using document.forms[formName].elements


    Hello;

    Objective: When click on Paypal radio button, alert the values of inputs.

    Problem: Works with every input but not with radio buttons.

    More info:

    I use this simple script to alert form values and it all works fine. But with radio buttons it doesn't work. Because there are 2 inputs with the same name. So this script alerts 'undefined'. But when I remove 1 of the radio buttons it obviously works fine because there is only 1 element with that name.

    What would be the solution to that?

    Thank you.
    javascript Code:
    function check_paypal(formName, div_id)
    	{
    		var firstname = document.forms[formName].elements["firstname"].value;
    		var lastname = document.forms[formName].elements["lastname"].value;		
     
    		var payment_option = document.forms[formName].elements["payment_option"].value; // This doesn't work
    		alert(payment_option);
    	}
    It all works fine except the radio button
    html Code:
    <form name="form_9244" id="form_9244" method="post" >
     
    <input type="text" name="firstname" id="firstname" value=""/>
    <input type="text" name="lastname" value="" />
     
    <input class="cc_option" name="payment_option" id="payment_option" type="radio" value="credit_card"  checked="checked"  />Credit Card
    <input id="payment_option" name="payment_option" type="radio" value="paypal" onclick="check_paypal('form_9244', 'paypal_9244')" />PayPal
     
    </form>
    I appreciate any sort of help.

    Thanks
  2. #2
  3. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    2,687
    Rep Power
    171
    Got it sorted. Not too crazy about the way I have to deal with radio buttons in JS though
    javascript Code:
    function check_paypal(formName, div_id)
    	{
    		var firstname = document.forms[formName].elements["firstname"].value;
    		var lastname = document.forms[formName].elements["lastname"].value;		
    		var radioCollection, checkedButton;
    		radioCollection = document.forms[formName].elements['payment_option'];
    				if(radioCollection)
    					{
    						for(var c = 0;c < radioCollection.length;c++)
    							{
    								if(radioCollection[c].checked)
    									{
    										alert(radioCollection[c].value);
    										break;
    									}
    							}
    						if(checkedButton)
    							{
    								var payment_option = checkedButton;
    								alert(payment_option);
    							}
    					}
    	}

IMN logo majestic logo threadwatch logo seochat tools logo