Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder bobleny's Avatar
    Join Date
    May 2007
    Posts
    258
    Thanks
    3
    Thanked 11 Times in 11 Posts

    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; 08-20-2011 at 05:41 PM.
    --www.firemelt.net--
    * No good deed goes unpunished.
    * Cheer up, the worst has yet to come...

  • #2
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    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 : "" ;
    }

  • #3
    Regular Coder bobleny's Avatar
    Join Date
    May 2007
    Posts
    258
    Thanks
    3
    Thanked 11 Times in 11 Posts
    Quote 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.

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

  • #4
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    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.


  •  

    Posting Permissions

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