How do I concatenate JavaScript variable names, form names, and element names to form a reference to an element?

How do I concatenate JavaScript variable names, form names, and element names to form a reference to an element?
ForExpertsExchange.txt
mfreeman2Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Michel PlungjanIT ExpertCommented:
Here is one way:

function InsureAnAnswerWasSelected(pCurrQuestion)            /* where pCurrQuestion = Q1, Q2, Q3, Q4, Q5 */
{
    var radGroup = document.forms["QuizForm"].elements[pCurrQuestion + "_Options"];

    for (var i=0; i<radGroup.length; i++)
    {
        if (radGroup[i].checked) return true; // we are happy
    }
    alert("An answer must be selected for question "+pCurrQuestion);
    return false;
}

Open in new window

0
Michel PlungjanIT ExpertCommented:
However if I were validating a form, I would do it like this:



function isChecked(radGroup) {
  for (var i=0; i<radGroup.length; i++) {
    if (radGroup[i].checked) return true; // we are happy
  }
  return false;
}

function validate(theForm) {
  for (var i=1;i<=5; i++) {
    var radGroup = theForm.elements["Q"+i+"_Options"];
    if (!isChecked(radGroup)) {
      alert('Please select an answer for question #'+(i+1))
      radGroup[0].focus();
      return false;
    }
  }
  return true; // allow submit
}

.
.
<form onSubmit="return validate(this)" ...>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mfreeman2Author Commented:
I actually ended up using eval() to slove the problem as follows:

function ValidateSelection(pQuestion)
{
    var jSelection = "";
    var jMsg = "";
 
    var jOptions = "QuizForm." + pQuestion + "Options";
    for (i=0; i< eval(jOptions).length; i++)
    {
        if (eval(jOptions)[i].checked)
        {
            jSelection = eval(jOptions)[i].value;
        }
    }
    if (jSelection.length = 0)
    {
        jMsg = jMsg + '\n' + "An answer must be selected.";
    }
    if (jMsg.length > 0)
    {
        alert(jMsg);
        return false;
    }
    else
    {
        return true;
    }
}  

However I accept your answers and award you the points because your solutions, in addition to being solutions that actually solve the problem, made me realize a couple of things. 1. It is not necessary to loop thru all 3 options (i.e. you exit the loop as soon as you find a checked option) and 2. I was on the right track by using the + sign as a concatenation operator but I had syntax problems. I also learned that I could use the concat() function to concatenate strings. Thanks much for your help and I gladly award you the 500 points (250 for each of your solutions).

mfreeman2
0
Michel PlungjanIT ExpertCommented:
Thanks for the accept
 I must however tell you that using eval in general is a poor design decision and in your case very sub-optimal
 All of your evals are evaluated forcing the browser to scan the dom each and every time. Also you are overdoing it on the eval here

Also not all browsers will understand QuizForm but needs document.QuizForm assuming QuizForm is the NAME of the form.
If it is the ID of the form you will need document.getElementById("QuizForm")

Please reconsider using one of the two suggestions below

function ValidateSelection(pQuestion)
{
    var jSelection = "";
    var jMsg = "";
 
    var jOptions = document.QuizForm.elements[pQuestion + "Options"]; // much safer and compatible method 
    for (i=0; i< jOptions.length; i++) // absolutely no need for eval here
    {
        if (jOptions[i].checked) // nor here
        {
            jSelection = jOptions[i].value; // nor here
        }
    }
    if (jSelection.length = 0)
    {
        jMsg = jMsg + '\n' + "An answer must be selected."; // I fail to see the need for concatenating ONCE
    }
    if (jMsg.length > 0)
    {
        alert(jMsg);
        return false;
    }
    else
    {
        return true;
    }
}   


--------------

This is much shorter and does the same thing


function ValidateSelection(pQuestion) {
  var jOptions = document.QuizForm.elements[pQuestion + "Options"]; // CANONICAL way to access a named field in a named form
  for (i=0; i< jOptions.length; i++) {
    if (jOptions[i].checked) return true; // no need to continue
  }
  alert("An answer must be selected.");
  return false;
}

Open in new window

0
mfreeman2Author Commented:
Thanks much mplungjan,

I did not realize that eval() had such a significant down side. I will in fact use one of the last two solutions...probably the shorter one. Thanks again for the additional information on eval().

mfreeman

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.