Web Analytics Made Easy -
StatCounter How do I use a string variable as a "name"? - CodingForum

Announcement

Collapse
No announcement yet.

How do I use a string variable as a "name"?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Resolved How do I use a string variable as a "name"?

    I have this function:
    Code:
    function SelectedRadio(form, name)
    {
    	for(var i = 0; i < form.name.length; i++)
    	{
    		if(form.name[i].checked == true)
    		{
    			return form.name[i].value;
    		}
    	}
    
    	return "Error!";
    }
    Form is a form object, and name is a string of the name of the radio button.

    I thought it was trying to use the variable name as the name of a field. For example:
    Code:
    function OnFormSubmit(form)
    {
    	SelectedRadio(form, "fruits")
    }
    Instead of form.fruits its using form.name. Basically I am trying to use the variable as a string.

    Is there anyway around this?
    Last edited by bobleny; Aug 20, 2011, 12:41 PM.
    --www.firemelt.net--
    * No good deed goes unpunished.
    * Cheer up, the worst has yet to come...

  • #2
    form[ name ][ i ]

    It would be better to pass a reference to the radio group:
    Code:
    function getRadioValue( group )
    {
      if( group.length )
        for( var i = 0; i < group.length && !group[ i ].checked; i++ )
        ;
    
      return group.length && i != group.length ? group[ i ].value : group.checked ? group.value : "" ;
    }

    Comment


    • #3
      Originally posted by Logic Ali View Post
      It would be better to pass a reference to the radio group:
      That's what I was doing because I couldn't figure out how to make it work the other way.

      Originally posted by Logic Ali View Post
      form[ name ][ i ]
      Oh, but why no dot (.) between form and [name]?
      --www.firemelt.net--
      * No good deed goes unpunished.
      * Cheer up, the worst has yet to come...

      Comment


      • #4
        You have a string as the name parameter. A string in javascript is represented by a sequence of characters surrounded by quotes.

        This is a string
        Code:
        "fruits"
        If you use form.name in that case it will become
        Code:
        from."fruits"
        which will result in an error, whereas form[name] will give
        Code:
        form["fruits"]
        which is perfectly legal.

        Comment

        Working...
        X