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
684 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
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…

728 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