Results 1 to 2 of 2

Thread: Get the value of Radio Input from a form

  1. #1
    Join Date
    Nov 2010
    Posts
    28
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Question Get the value of Radio Input from a form

    I would like to know how to get the value of a selected radio button in a form. Suppose I want to use the following code:

    HTML Code:
    <html>
    <head>
    <script type="text/javascript">
    function score_form()
    {
    var opt = document.question.opt.value;
    var element = document.getElementById('code');
    element.innerHTML = "<form><fieldset>You have selected <b>" + opt + "</b>.</fieldset></form>";
    }
    </script>
    </head>
    
    <body>
    <div id="code">
    <form onsubmit="score_form()" name="question">
    <fieldset>
    <input type="radio" name="opt" value="option1" />Option 1<br />
    <input type="radio" name="opt" value="option2" />Option 2<br />
    <input type="submit" value="Score" />
    </fieldset>
    </form>
    </div>
    </body>
    </html>
    I get a value of undefined. Why? How can I get this code to work properly? Thanks in advance.

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Code:
    <html>
    <head>
    <script type="text/javascript">
    function score_form(form){
    	var opts = form.elements['opt[]'], opt, element = document.getElementById('code');
    	for (var i = opts.length - 1; i > -1; --i){
    		if(opts[i].checked){
    			opt = opts[i].value;
    			break;
    		}
    	}
    	if(opt){
    		element.innerHTML = "<form><fieldset>You have selected <b>" + opt + "</b>.</fieldset></form>";
    	}
    	return false;
    }
    </script>
    </head>
    
    <body>
    <div id="code">
    <form onsubmit="return score_form(this);" name="question">
    <fieldset>
    <input type="radio" name="opt[]" value="option1" />Option 1<br />
    <input type="radio" name="opt[]" value="option2" />Option 2<br />
    <input type="submit" value="Score" />
    </fieldset>
    </form>
    </div>
    </body>
    </html>
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •