Solved

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

Posted on 2010-08-16
5
681 Views
Last Modified: 2012-05-10
How do I concatenate JavaScript variable names, form names, and element names to form a reference to an element?
ForExpertsExchange.txt
0
Comment
Question by:mfreeman2
  • 3
  • 2
5 Comments
 
LVL 75

Assisted Solution

by:Michel Plungjan
Michel Plungjan earned 500 total points
ID: 33443990
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
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
ID: 33444018
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
 

Author Closing Comment

by:mfreeman2
ID: 33451232
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
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 33451926
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
 

Author Comment

by:mfreeman2
ID: 33462211
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

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Today I would like to talk about localizing (Internationalization) JavaScript applications. Introduction When creating an application that is going to be used by many people around the globe, it is important to remember that not everyone speak…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question